gpt4 book ai didi

Java Process无法通过Runtime.getRunTime().exec()获取InputStream

转载 作者:太空狗 更新时间:2023-10-29 11:38:35 25 4
gpt4 key购买 nike

try {

String str;
Process process = Runtime.getRuntime().exec("bash /home/abhishek/workspace/Pro/run");
InputStream isout = process.getInputStream();
InputStreamReader isoutr = new InputStreamReader(isout);
BufferedReader brout = new BufferedReader(isoutr);
while ((str = brout.readLine()) != null) {
System.out.println(str);
}

} catch (IOException e) {
e.printStackTrace();
}

代码在从进程获取 InputStream 时存在问题,因为如果我从我的终端运行 Shell 脚本,它运行得很好,但是如果我这样运行脚本,str 总是空的,

我正在使用此代码将 Shell 脚本的输出直接获取到 Java,而不是将脚本输出写入文件

有没有其他方法可以实现这个,或者我怎样才能使用当前方法解决问题

最佳答案

我认为错误流返回了一些东西,因此您可以尝试从 Process.getErrorStream() 中检查一些东西。

您还应该等待创建的进程,以防止您的主程序在它之前完成。使用 Process.waitFor();

public class TestMain {
private static final String BASH_CMD = "bash";

private static final String PROG = "/home/abhishek/workspace/Pro/run";

private static final String[] CMD_ARRAY = { BASH_CMD , PROG };

public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String command = null;
try {
while ((command = reader.readLine()) != null) {
System.out.println("Command Received:" + command);
}
} catch (Exception ex) {
ex.printStackTrace();
// failed to listening command
}

}
}).start();
Process process = null;
try {
ProcessBuilder processBuilder = new ProcessBuilder(CMD_ARRAY);
process = processBuilder.start();
InputStream inputStream = process.getInputStream();
setUpStreamGobbler(inputStream, System.out);

InputStream errorStream = process.getErrorStream();
setUpStreamGobbler(errorStream, System.err);

System.out.println("never returns");
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

public static void setUpStreamGobbler(final InputStream is, final PrintStream ps) {
final InputStreamReader streamReader = new InputStreamReader(is);
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(streamReader);
String line = null;
try {
while ((line = br.readLine()) != null) {
ps.println("process stream: " + line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}

关于Java Process无法通过Runtime.getRunTime().exec()获取InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14727579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com