// 对文件进行编译
Process compileProcess = Runtime
.getRuntime()
.exec("C:\\JudgeOnline\\bin\\gcc\\bin\\gcc.exe -fno-asm -s -w -O1 -DONLINE_JUDGE -o C:\\temp\\1002\\Main C:\\temp\\1002\\1468287854.c".getBytes()");
BufferedReader reader = new BufferedReader(new InputStreamReader(
compileProcess.getInputStream()));
StringBuilder comResult = new StringBuilder();
String result = reader.readLine();
while (result != null) {
comResult.append(result).append("\n");
result = reader.readLine();
} reader.close();
compileProcess.destroy(); System.out.println("comResult=" + comResult.toString());exec中参数传递的是对1468287854.c文件进行编译,并且捕获输出到comResult中,怎么捕获不到呢?即使参数有问题,编译不通过,也应该有提示信息啊?
求解释!!!!
对于Process,也有2个流推荐使用 ProcessBuilder,并将ErrorStream合并到InputStream里去,这样就可以完美解决了,只要是进程的输出,不管是正常输出,还是error输出,都可以捕获
InputStream[] inStream = new InputStream[]{process.getInputStream(),process.getErrorStream()};
File f = new File("C:\\1001.out");
FileWriter out = new FileWriter(f);
for(int i=0;i < ins.length;i++)
{
int ch;
while((ch=inStream[i].read())!=-1)
out.write(ch);
}
out.close();
没有的话 inputstream里面没有东西给你读的
但是我觉得你没有必要去调查这个问题,你直接在命令中加入重定向符,将输出和error写到文件里就OK了。
public class Compile { public static boolean compileSource(CompileType compileType)
throws IOException { File file = new File(compileType.getFilePath()); // 判断文件是否存在
if (!file.exists()) {
throw new RuntimeException("文件不存在");
}
// 对文件进行编译
Process compileProcess = Runtime
.getRuntime()
.exec("C:\\JudgeOnline\\bin\\gcc\\bin\\gcc.exe -fno-asm -s -w -O1 -DONLINE_JUDGE -o C:\\temp\\1002\\Main C:\\temp\\1002\\1468287854.c");
BufferedReader reader = new BufferedReader(new InputStreamReader(
compileProcess.getInputStream()));
StringBuilder comResult = new StringBuilder();
String result = reader.readLine();
while (result != null) {
comResult.append(result).append("\n");
result = reader.readLine();
} reader.close();
compileProcess.destroy(); System.out.println("comResult=" + comResult.toString()); // 保存编译结果
compileType.setCompileResult(comResult.toString()); // 判断编译是否成功
if (comResult.toString().contains(": error")) {
compileType.setError(true);
} // 如果编译成功,则进行运行
if (!compileType.isError()) { } return false;
}