4

我正在尝试启动命令外壳并向其发送“dir”命令。但它不起作用。我正在使用的代码基于此处的 SO 问题:Run external program concurrently and communication 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.
4

2 回答 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) {}
于 2012-12-23T11:08:43.470 回答
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) {}

    }
}
于 2012-12-24T12:58:50.960 回答