使用ProcessBuilder将命令发送到外部进程

时间:2012-12-23 10:54:57

标签: java command-line process processbuilder

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

2 个答案:

答案 0 :(得分: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) {}

答案 1 :(得分: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) {}

    }
}