4

I'm trying to start a command shell and send the 'dir' command to it. But it isn't working. The code I'm using is based off of the SO question here: 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();

}

The process is being triggered since I see the following output. But if I try passing any command, it doesn't respond with an output or anything:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
Community
  • 1
  • 1
Plasty Grove
  • 2,807
  • 5
  • 31
  • 42
  • 3
    Tried adding a new line \n on that? Also you do know you can use java.io.File if you want a directory listing...? – Adam Dec 23 '12 at 10:57
  • Wow, you've got to be kidding me! Yup, that works. Yea, I know this is not the way to get a directory listing, I'm just trying to get the ProcessBuilder thing to work. If you could post it as an answer I'll accept it – Plasty Grove Dec 23 '12 at 11:02

2 Answers2

2

you are executing the command cmd.exe within the command prompt which return the result

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

how about doing this

Process p=Runtime.getRuntime().exec("cmd /c dir"); 

if you want your program to run behind and receive values

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) {}
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • Thanks for the reply, but I need the command prompt to run continuously in the background and pass commands to it one at a time and get responses – Plasty Grove Dec 23 '12 at 11:10
  • Thanks for the follow-up. But I'm unable to get it to work. When I try running it, it doesn't display anything. I'm using String command = "cmd.exe"; Process pr = Runtime.getRuntime().exec(command); in the try block. Am I doing something wrong? Do I need to start the thread explicitly? – Plasty Grove Dec 24 '12 at 03:41
1

Take look at this program. There is a main program which has a GUI for adding two numbers. Behind the screen on the terminal there's another program running which does the same addition operation. Both runs on the same time.

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) {}

    }
}
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • Thanks so much for posting this, I'll go through it and see if I can adopt it. But my initial problem was resolved by adding a new line at the end of the command string – Plasty Grove Dec 25 '12 at 07:14
  • I would, but it isn't the right answer to my question. I'm grateful for your help and I'm sure it'll be useful to a lot of folks, but Adam gave me the answer I was looking for – Plasty Grove Dec 25 '12 at 07:20
  • Okay take a review at the code given above.some or the other way it can be beneficial. – Nidhish Krishnan Dec 25 '12 at 07:23