1

In one commend , I'm trying to send data to System.out like this:

And in another command I'm trying to get this data from System.in.

It's strange because, it works once of many tries. I can try to run it 10 times and it's still inReader.ready() == false, and when I run it for example 11th time , it works.

Why ? How can I fix this? How to make it work everytime ?

Thanks, in advance !

John Moon
  • 11
  • 2
  • From [doc](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/InputStreamReader.html#ready%28%29): `Returns: True if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.` So it is useless to check - just call read to read the data and the data will go into the program as the program earlier in the chain output something – nhahtdh Nov 10 '12 at 09:53

2 Answers2

1

You can't read your InputStream that way, since the data may not have been arrived at the second process yet. You can either read character by character, with something like:

InputStreamReader inReader = new InputStreamReader(System.in); 
int data = inReader.read();
while (data != -1){
    ...
    data = inReader.read();
}

or simple read the input line by line, using:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

while ((String line = br.readLine()) != null) {
    ...
}
MikeN
  • 887
  • 5
  • 18
0

If your objective is to execute a shell command, don't use System.out but Runtime.getRuntime().exec(cmd) instead. Check out this question for more details.

Community
  • 1
  • 1
mac
  • 5,627
  • 1
  • 18
  • 21