Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
执行java命令时如何获取错误消息?_Java - Fatal编程技术网

执行java命令时如何获取错误消息?

执行java命令时如何获取错误消息?,java,Java,我在java代码中调用位于jar文件某处的类(使用java-classpath/file.jar classname) 这很有效,但只有在命令格式正确的情况下才有效。如果我犯了错误,getRuntime().exect(命令)就是什么也不说。贝娄我有工作命令调用。我想在命令不起作用时得到错误消息。如果我在cmd(windows)中出错,我会得到一个正确的错误,我可以修复它。但不是在我的java应用程序中 我留下了一个“if(input.ready()”,因为如果我不这样做,当命令行不正确时,程序

我在java代码中调用位于jar文件某处的类(使用java-classpath/file.jar classname)

这很有效,但只有在命令格式正确的情况下才有效。如果我犯了错误,getRuntime().exect(命令)就是什么也不说。贝娄我有工作命令调用。我想在命令不起作用时得到错误消息。如果我在cmd(windows)中出错,我会得到一个正确的错误,我可以修复它。但不是在我的java应用程序中

我留下了一个“if(input.ready()”,因为如果我不这样做,当命令行不正确时,程序就会冻结。执行“input.readLine()”时会发生这种情况

对于如何从执行的命令中获取错误,您有什么建议吗


谢谢你

这不是你想要的吗?

使用getErrorStream:

BufferedReader errinput = new BufferedReader(new InputStreamReader(
                child.getErrorStream()));

当处理来自不同流的输入时,最好在不同的线程中执行(因为那些调用(
readLine
等)是阻塞调用。

这里有一段更完整的代码,可以打印出通过进程/运行时运行某些
命令时收到的错误:


看起来他还是想等待进程终止。我同意,但你不能在同一个线程中并行读取两个流。@glowcoder-因为你不知道下一行将从哪个流中读取。@MByD因此,如果我启动线程读取流,这只会避免阻塞我的主进程。但readLine仍会阻塞下一行e线程,不是吗?是的,但它将是一个单独的线程。我看到了一个很好的例子,我仍然在寻找它。当我找到它时,请告诉你。
BufferedReader errinput = new BufferedReader(new InputStreamReader(
                child.getErrorStream()));
final String command = "/bin/bash -c cat foo.txt | some.app";
Process p;
    try {
        p = Runtime.getRuntime().exec(command);
    } catch (final IOException e) {
        e.printStackTrace();
    }

    //Wait to get exit value
    try {
        p.waitFor();
        final int exitValue = p.waitFor();
        if (exitValue == 0)
            System.out.println("Successfully executed the command: " + command);
        else {
            System.out.println("Failed to execute the following command: " + command + " due to the following error(s):");
            try (final BufferedReader b = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
                String line;
                if ((line = b.readLine()) != null)
                    System.out.println(line);
            } catch (final IOException e) {
                e.printStackTrace();
            }                
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }