gpt4 book ai didi

java - 使用 ProcessBuilder 向外部进程发送命令

转载 作者:搜寻专家 更新时间:2023-11-01 03:09:14 24 4
gpt4 key购买 nike

我正在尝试启动命令外壳并向其发送“dir”命令。但它不起作用。我使用的代码基于此处的 SO 问题:Run external program concurrently and communicate with it through stdin / stdout

public static void main(String[] args) throws IOException, InterruptedException {

String params[] = {"cmd.exe"};
ProcessBuilder pb = new ProcessBuilder(params);
Process proc = pb.start();

final Scanner in = new Scanner(proc.getInputStream());
Thread t = new Thread() {
public void run() {
while (in.hasNextLine())
System.out.println(in.nextLine());
}
};

t.start();
PrintWriter out = new PrintWriter(proc.getOutputStream());
Thread.sleep(5000);

out.write("dir");
out.flush();

}

进程被触发,因为我看到以下输出。但是如果我尝试传递任何命令,它不会以输出或任何方式响应:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

最佳答案

您正在命令提示符下执行命令 cmd.exe 并返回结果

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

这个怎么样

Process p=Runtime.getRuntime().exec("cmd /c dir"); 

如果你想让你的程序落后并接收值

private ExecutorService execService = Executors.newFixedThreadPool(1);

try {
execService.submit(new Runnable() {

@Override
public void run() {
try {
//define the task over here ...
//eg. String command= "your command";
// Process pr = rt.exec(command);
} catch (IOException ex) {}
}
});
} catch (IOException ex) {}

关于java - 使用 ProcessBuilder 向外部进程发送命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14010375/

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