// 对文件进行编译
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中,怎么捕获不到呢?即使参数有问题,编译不通过,也应该有提示信息啊?
求解释!!!!

解决方案 »

  1.   

    compileProcess.getInputStream()应该是output吧
      

  2.   

    将exec中的参数换成tasklist(查看进程)命令,就可以正常捕获啊 ,这是为什么呢?
      

  3.   

    程序输出,有正常输出流和错误输出流,就像java里的System.out和System.err一样
    对于Process,也有2个流推荐使用 ProcessBuilder,并将ErrorStream合并到InputStream里去,这样就可以完美解决了,只要是进程的输出,不管是正常输出,还是error输出,都可以捕获
      

  4.   

    这样试过,还是不行Process process=Runtime.getRuntime().exec(cmd);
        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();
      

  5.   

    能不能给出一个ProcessBuilder的例子?
      

  6.   

    有吧,当参数是tasklist时,就可以正常捕获啊 
      

  7.   

    你执行一下你那一句就知道有没有了嘛……
    没有的话 inputstream里面没有东西给你读的
      

  8.   

    肯定是哪里有问题。
    但是我觉得你没有必要去调查这个问题,你直接在命令中加入重定向符,将输出和error写到文件里就OK了。
      

  9.   

    可是明明应该有啊 ,在dos下运行就有,嗯,重定向可以解决
      

  10.   


    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;
    }
      

  11.   

    我把你执行的命令改成“cmd /C dir”,在我这里的控制台上完全没有问题。