我无法从运行时exec获得预期的输出

时间:2016-10-26 02:52:38

标签: java

我执行了这段代码:

Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
System.out.println(proc.toString());
String proc1 = proc.toString();

但是我无法获得kafka_metrics.sh的内容。相反,我得到java.lang.UNIXProcess@5fd0d5ae作为输出。我应该包括什么才能获得该文件的内容?

2 个答案:

答案 0 :(得分:0)

愿这就是你要找的。

Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
String s = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}

// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

答案 1 :(得分:0)

您正在打印Process对象。

获取执行流程的内容,您需要获取输入流并将该流传递给阅读器

    Process process = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
    InputStream is = process.getInputStream();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        br.lines().forEach(System.out::println);
    }