John Moon
John Moon

Reputation: 11

Communication between unix commands in Java

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 !

Upvotes: 1

Views: 243

Answers (2)

mac
mac

Reputation: 5647

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.

Upvotes: 0

MikeN
MikeN

Reputation: 907

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

Upvotes: 1

Related Questions