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

标签 java command-line process processbuilder

我正在尝试启动命令外壳并向其发送“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/

相关文章:

java - Spring注册对象销毁方法

java - 如何使用 JDBC 在 spring-session 中初始化模式

linux - 别名 <cmd> 到 "do X then <cmd>"透明

linux - 根据linux中的字符位置排序

java - 无法运行Shell脚本

c++ - 如果 stdin 被另一个进程的管道替换,则 std::getline 中断

java - 如果有更好的方法在java中编写这个if语句

java - 编译器错误找不到符号 - Java

linux - 我怎样才能使 svnlook TreeView 只有 2 级?

web-applications - 先设计界面还是写代码哪个更好?