0

I have the following code in java that calls the date command in the command prompt:

// prepare command prompt runtime and process
Runtime runtime = null;
Process process = null;

// prepare output stream
OutputStream outputStream = null;

try {
   runtime = Runtime.getRuntime(); // instantiate runtime object
   process = runtime.exec("date"); // get the current date in command prompt

   // read the output of executing date command
   outputStream = process.getOutputStream();

   // output the date response
   System.out.println(outputStream);

   process.waitFor(); // wait for the date command to finish
} catch(Exception e) {
  e.printStackTrace();
} // end catch

How can I read the outputStream value for me to be able to use the System.output.println()

epsac
  • 198
  • 5
  • 17
  • Is using the command line `date` program just a test or do you really think you need to get the date this way? – trojanfoe Nov 25 '11 at 07:35
  • possible duplicate of [Capturing stdout when calling Runtime.exec](http://stackoverflow.com/questions/882772/capturing-stdout-when-calling-runtime-exec) – Giovanni Nov 25 '11 at 07:41
  • It's not actually the date command but the sqlldr (Oracle SQL*Loader) command that I'm executing here... I just put date to simplify my question. – epsac Nov 25 '11 at 07:42
  • Amazingly enough you can read an OutputStream with the `read()` method. ;) However reading lines with a BufferedReader may be more useful in some cases. e.g. if there is more than one line. – Peter Lawrey Nov 25 '11 at 08:14

2 Answers2

2

You don't read the output stream, you write to it to pass data to process. To read the data from process use

BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
br.readLine();

The code is for string output of process. Of course if your process outputs data in other way you have to change the wrappers around process.getInputStream()

Update: I think it is in some way confusing that we use getInputStream to actually read process output :) The reason is that initially basic classes OutputStream and InputStream were named so relatively to the code that uses them (the code you write). So when you use OutputStream you actually use it as output for your program. When you use process.getOutputStream you don't get process' output but instead get your program output which is piped to process input. When you use process.getInputStream you get input for your program which obtains data piped from process' output.

pavel_kazlou
  • 1,995
  • 4
  • 28
  • 34
0

you can do like this way without using OutputStream object

Process p = Runtime.getRuntime().exec("date");  
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));  
StringBuffer sb = new StringBuffer();  
String line;  
while ((line = br.readLine()) != null) {  
  sb.append(line).append("\n");  
}  
String answer = sb.toString(); 
System.out.println(answer);
Pratik
  • 30,639
  • 18
  • 84
  • 159