1

I am running a command line command from java:

ping localhost > output.txt

The command is send via a Java like this:

Process pr = rt.exec(command);

For some reason the file is not created, but when i run this command from the command line itself, the file does create and the output is in that file.

Why doesn't the java command create the file?

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Michael A
  • 5,770
  • 16
  • 75
  • 127
  • 2
    Check [this post](http://stackoverflow.com/questions/3643939/java-process-with-input-output-stream) – fvu Jul 25 '12 at 12:48

4 Answers4

4

Because you haven't directed it to a file.

On the command line, you've requested that it be redirected to a file. You have to do the same thing in Java, via the InputStream provided by the Process object (which corresponds to the output stream of the actual process).

Here's how you get the output from the process.

InputStream in = new BufferedInputStream( pr.getInputStream());

You can read from this until EOF, and write the output to a file. If you don't want this thread to block, read and write from another thread.

InputStream in = new BufferedInputStream( pr.getInputStream());
OutputStream out = new BufferedOutputStream( new FileOutputStream( "output.txt" ));

int cnt;
byte[] buffer = new byte[1024];
while ( (cnt = in.read(buffer)) != -1) {
   out.write(buffer, 0, cnt );
}
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
3

1. After successfully executing the command from Java program, you need to read the output, and then divert the Output to the file.

Eg:

    Process p = Runtime.getRuntime().exec("Your_Command");

    InputStream i = p.getInputStream();

    InputStreamReader isr = new InputStreamReader(i);

    BufferedReader br = new BufferedReader(isr);


    File f = new File("d:\\my.txt");

    FileWriter fw = new FileWriter(f);            // for appending use (f,true)

    BufferedWriter bw = new BufferedWriter(fw);

    while((br.readLine())!=null){


         bw.write(br.readLine());           // You can also use append.
  }
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
1

Complementing Andy's answer, I think you MUST read this article: http://www.javaworld.com/jw-12-2000/jw-1229-traps.html.

It is very important for who needs to deal with external processes in Java.

davidbuzatto
  • 9,207
  • 1
  • 43
  • 50
1

I you want to keep it simple, and you are using Windows, try:

Process pr = rt.exec("cmd /c \"ping localhost > output.txt\"");
AlexDev
  • 4,049
  • 31
  • 36