【问题标题】:Send a command to external process using ProcessBuilder使用 ProcessBuilder 向外部进程发送命令
【发布时间】:2012-12-10 05:28:40
【问题描述】:

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

【问题讨论】:

  • 试过添加一个新行 \n 吗?你也知道如果你想要一个目录列表你可以使用 java.io.File...?
  • 哇,你一定是在开玩笑吧!是的,这行得通。是的,我知道这不是获取目录列表的方法,我只是想让 ProcessBuilder 工作。如果您可以将其发布为答案,我会接受它

标签: java command-line process processbuilder


【解决方案1】:

您正在返回结果的命令提示符内执行命令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) {}

【讨论】:

  • 感谢您的回复,但我需要命令提示符在后台连续运行,并一次将命令传递给它并获得响应
  • 感谢您的跟进。但我无法让它工作。当我尝试运行它时,它不显示任何内容。我正在使用 String command = "cmd.exe";进程 pr = Runtime.getRuntime().exec(command);在尝试块中。难道我做错了什么?我需要显式启动线程吗?
【解决方案2】:

看看这个程序。 有一个主程序,它有一个用于添加两个数字的 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) {}

    }
}

【讨论】:

  • 非常感谢您发布这个,我会通过它,看看我是否可以采用它。但是我最初的问题是通过在命令字符串的末尾添加一个新行来解决的
  • 我愿意,但这不是我问题的正确答案。我很感谢你的帮助,我相信它对很多人都有用,但亚当给了我我一直在寻找的答案
  • 好的,对上面给出的代码进行审查。一些或其他方式可能是有益的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 2011-08-25
  • 2012-06-26
  • 2017-11-20
  • 2011-01-09
相关资源
最近更新 更多