gpt4 book ai didi

java - 如何让Runtime.getRuntime().exec一一执行命令并获取输出而不是执行所有命令

转载 作者:行者123 更新时间:2023-11-30 04:00:45 24 4
gpt4 key购买 nike

我正在尝试从我的 java 应用程序运行 *.bat 文件(它能够运行多个命令并一一检索输出)。 我的目的是发送一个命令,读取输出,使用此输出作为第二个命令,然后再次检索输出

为了实现这一目标,通过 Runtime.getRuntime().exec,我将多个命令作为输入传递给 PrintWriter。问题是,完成所有步骤后,只有我可以通过 buffer 读取 *.bat 的输出,但我的目的是运行一个命令获取输出并操作此输出以发送第二个命令

不幸的是,它不起作用。有什么解决办法吗?..

我想从这个链接发送多个命令到 Runtime.getRuntime().exec ( How to execute cmd commands via Java )

以下是我从上面链接获得的相同代码

String[] command =
{
"cmd",
};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("dir c:\\ /A /Q");
// write any other commands you want here
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}

最佳答案

在您的情况下,我不会使用线程,您需要一个顺序执行路径。

关于java - 如何让Runtime.getRuntime().exec一一执行命令并获取输出而不是执行所有命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22040133/

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