Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Excecuting dos (or unix) commands from Java.

Status
Not open for further replies.

Azathoth

Technical User
Jul 14, 2003
61
US
I'm trying to excecute a command in dos from within my Java program, something like ("java " + commandline), but I can't get it to work.

This lcode is in Driver.java:
Code:
String commandline = "Cat file.txt";
Runtime rt1 = Runtime.getRuntime();
Process pr1 = rt1.exec("java " + commandline);

And this is my Cat.java, it prints the contents of the file(s) passed to it as arguments:
Code:
import java.io.*;

public class Cat {

   public static void main(String argv[]) {
      int counter = 0;
      while(counter < argv.length)
      {
         FileInputStream fin1;
         BufferedInputStream bin2;
  
         try {
            fin1 = new FileInputStream(argv[counter]);
         }
         catch (FileNotFoundException f) {
            throw new Error("The system cannot find the file " + argv[0]);
         }

         bin2 = new BufferedInputStream(fin1);
         byte[] bytes;
         boolean end;

         try {
            do {
               int avail = bin2.available();
               end = (avail == 0);
               bytes = new byte[avail];
               bin2.read(bytes);
               System.out.print(new String(bytes));
            } 
            while (!end);
            bin2.close();
            System.out.println("");
         }
         catch (IOException ex) {
            throw new Error("IO Error");
        }    
      counter++;
      }
   }
}

It looks like the command line is formatted correctly, but nothing happens upon execution...any help would be greatly appreciated.
 
You need to capture the IO streams from the Process object (see the documenation on Process to see how to get the streams).

--------------------------------------------------
Free Database Connection Pooling Software
 
I've taken a look at the documenation on Process, but can't really make any sense of it. Any chance you could you provide a simple example?
 
InputStream is = process.getInputStream();
OutputStream os = process.getOutputStream();

--------------------------------------------------
Free Database Connection Pooling Software
 
If your program is a javaprogram, you don't need the Runtime-class.

Just call
Code:
Cat.main ("file.txt");
in Driver.java.

I guess the others have overseen that detail :)

Note: Either both classes have to share the same package-declaration, or 'Cat' has to be found in the classpath.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top