[英]Call a C executable with input and output redirection from Java
我具有以下文件夾結構:
從解析器中的Java文件中,我要執行mylexer程序並等待結果。 我有以下代碼:
public static String getTokensFromFile(String path) {
String s = null;
StringBuilder sb = new StringBuilder(path);
try {
Runtime rt = Runtime.getRuntime();
String[] command = {"mylexer", "<", path, ">", "output.txt"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.directory(new File("../Lexer"));
Process pr = pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(pr.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(pr.getErrorStream()));
while ((s = stdError.readLine()) != null) {
sb.append(s+"\n");
}
}catch(Exception e) {
System.out.println(e);
}
return (sb.toString().length() > 0)? sb.toString() : "";
}
我沒有得到任何結果,程序永遠不會結束執行,如果執行此String[] command = {"./mylexer", "<", path, ">", "output.txt"};
它說找不到該文件。 我該如何實現?
我也在終端上做到了
../Lexer/mylexer < /Users/jacobotapia/Documents/Compiladores/Proyecto/Lexer/sample.txt > output.txt
但這在Java上不起作用。
使用<
和>
輸入和輸出重定向由外殼程序(sh,bash或您使用的任何東西)執行。 除非您從ProcessBuilder調用外殼程序,否則它們不能在ProcessBuilder中使用此語法。
但是,ProcessBuilder對其使用redirectInput
和redirectOutput
方法開始的進程的輸入和輸出進行重定向具有自己的支持。 以下應該為您工作:
String[] command = {"mylexer"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectInput(new File(path));
pb.redirectOutput(new File("output.txt"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.