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

4
我正在尝试启动一个命令行并向其发送“dir”命令,但它没有起作用。我使用的代码是基于此SO问题的:同时运行外部程序并通过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.

3
在那上面尝试添加一个新行 \n 了吗?你也知道如果你想要一个目录列表的话,可以使用java.io.File吗...? - Adam
哇,你一定是在开玩笑吧!是的,它有效。是的,我知道这不是获取目录列表的方法,我只是想让ProcessBuilder正常工作。如果你能把它发布为答案,我会接受它。 - Plasty Grove
2个回答

2

您正在命令提示符中执行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) {}

谢谢回复,但我需要命令提示符在后台持续运行,并逐个传递命令并获取响应。 - Plasty Grove
谢谢您的跟进。但是我无法让它工作。当我尝试运行它时,它没有显示任何内容。我在try块中使用了String command = "cmd.exe"; Process pr = Runtime.getRuntime().exec(command);。我做错了什么吗?我需要显式启动线程吗? - Plasty Grove

1

看看这个程序。 有一个主程序,它有一个GUI用于添加两个数字。 在终端的屏幕后面,还有另一个正在运行的程序,执行相同的加法操作。两者同时运行。

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Myapp extends javax.swing.JFrame {
    public Myapp() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        first = new javax.swing.JTextField();
        jLabel189 = new javax.swing.JLabel();
        jLabel183 = new javax.swing.JLabel();
        second = new javax.swing.JTextField();
        jLabel184 = new javax.swing.JLabel();
        sum = new javax.swing.JTextField();
        signbut = new javax.swing.JButton();
        signbut1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        first.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel189.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel189.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel189.setText("First Number");

        jLabel183.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel183.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel183.setText("Second Number");

        second.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel184.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel184.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel184.setText("Sum");

        sum.setBackground(new java.awt.Color(255, 255, 255));
        sum.setEditable(false);
        sum.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        sum.setDisabledTextColor(new java.awt.Color(255, 255, 255));

        signbut.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        signbut.setText("CLEAR");
        signbut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signbutActionPerformed(evt);
            }
        });

        signbut1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        signbut1.setText("ADD");
        signbut1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signbut1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel189, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(first, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel183, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(second, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel184, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(70, 70, 70)
                        .addComponent(signbut, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(signbut1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(26, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel189)
                    .addComponent(first, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel183)
                    .addComponent(second, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel184)
                    .addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(signbut)
                    .addComponent(signbut1))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void signbutActionPerformed(java.awt.event.ActionEvent evt) {
       sum.setText("");
       first.setText("");
       second.setText("");
    }

    private void signbut1ActionPerformed(java.awt.event.ActionEvent evt) {
      try
      {
       int a=Integer.parseInt(first.getText());
       int b=Integer.parseInt(second.getText());
       int c=a+b;
       sum.setText(""+c);
      }catch(Exception e){
       sum.setText("");
       first.setText("");
       second.setText("");}
    }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                BackProgram b=new BackProgram();
                b.getBackendWorker();
                new Myapp().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTextField first;
    private javax.swing.JLabel jLabel183;
    private javax.swing.JLabel jLabel184;
    private javax.swing.JLabel jLabel189;
    private javax.swing.JTextField second;
    private javax.swing.JButton signbut;
    private javax.swing.JButton signbut1;
    private javax.swing.JTextField sum;
    // End of variables declaration
}

class BackProgram
{
   private ExecutorService execService = Executors.newFixedThreadPool(1);
   public void getBackendWorker() {
        try {
            execService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                          while(true)
                            {
                            try{
                                    System.out.println("(BackProgram Class) Enter two Numbers:");
                                    Scanner s=new Scanner(System.in);
                                    int a=s.nextInt();
                                    int b=s.nextInt();
                                    int c=a+b;
                                    System.out.println("Number Sum is:"+c);
                                }catch(Exception ed){}
                            }
                        } catch (Exception ex) {}
                }
            });
           } catch (Exception ex) {}

    }
}

非常感谢您发布这个,我会仔细阅读并看看是否可以采用它。但是我的初始问题已通过在命令字符串末尾添加新行来解决。 - Plasty Grove
我很感激你的帮助,对于许多人来说,它肯定是有用的,但这不是我问题的正确答案。Adam 给了我我想要的答案。 - Plasty Grove
好的,请仔细查看上面给出的代码,它可能以某种方式是有益的。 - Nidhish Krishnan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接