输出bash脚本的结果



例如,如果我选择运行一个bash脚本,该脚本将输出(回显)时间,例如CheckDate.sh。我如何从Java中运行它,然后在Java程序中打印bash脚本的结果(日期)?

试试这个代码。

String result = null;
try {
    Runtime r = Runtime.getRuntime();                    
    Process p = r.exec("example.bat");
    BufferedReader in =
        new BufferedReader(new InputStreamReader(p.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        result += inputLine;
    }
    in.close();
} catch (IOException e) {
    System.out.println(e);
}

一种方法是在Process对象中分配脚本执行,并从其输入流中检索脚本输出。

try {
    // Execute command
    String command = "ls";
    Process process = Runtime.getRuntime().exec(command);
    // Get the input stream and read from it
    InputStream in = process.getInputStream();
    int c;
    while ((c = in.read()) != -1) {
        process((char)c);
    }
    in.close();
} catch (IOException e) {
    LOGGER.error("Exception encountered", e);
}

另一种方法是让bash脚本将其输出写入一个文件,然后从Java中读回该文件。

祝你好运。

java.lang.Process类就是用于此类目的的。您可以使用(更简单的)java.lang.Runtime.exec函数或(更复杂的)java.lang.ProcessBuilder类在Java中运行外部进程。最后,两者都为您提供了所述java.lang.Process的一个实例,您可以调用其getInputStream方法来获取流,从中可以读取其输出。

有关更多信息,请参阅Javadoc。

最新更新