2

我正在尝试远程执行 .bat 文件并实现以下代码行:

ProcessBuilder processBuilder = new ProcessBuilder(command);
    final Process process = processBuilder.start();

    InputStream stderr = process.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;


    while ((line = br.readLine()) != null) {
        System.out.println(line);

    }
    process.waitFor();
    System.out.println("Waiting ...");

    System.out.println("Returned Value :" + process.exitValue());

但是我的程序卡在了while循环中。它显示的错误是:

CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.

它永远不会退出while循环。但它会成功执行脚本。任何形式的帮助表示赞赏。谢谢

4

2 回答 2

3

您需要确保您也在处理 stderr,并且您应该在单独的线程中处理两个流。

阅读本文并确保您遵循所有建议。

编辑:查看您编写的代码,您似乎已经从这篇精确的文章中复制了代码。事实上,它看起来像清单 4.3 (MediocreExecJavac.java)。

于 2010-09-27T21:22:38.757 回答
2

在 .start() 之前添加 redirectErrorStream(true) 并阅读 getInputStream()。这将读取 stderr 并将其与 stdout 合并为一个可以使用 getInputStream() 读取的响应。

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    final Process process = processBuilder.start();

    InputStream stderr = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;


    while ((line = br.readLine()) != null) {
        System.out.println(line);

    }
    process.waitFor();
    System.out.println("Waiting ...");

    System.out.println("Returned Value :" + process.exitValue());
于 2014-01-16T20:41:48.123 回答