-2

I'm getting the InputStream from a process and printing it like this:

String line = null;
var iStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = iStream.readLine()) != null) {
    System.out.print(line);
}

The issue is that when I print line, it's spaces are omitted, e.g., if I execute ls in the child process, it prints all directory contents concatenated, like this:

dir1dir2file1file2

What the hell is happening here?


Obs.: it works fine when I call inheritIO when instantiating the ProcessBuilder, but I have reasons not to use this method.

  • It is not 'omitting spaces'. `readLine()` removes the line terminator, and you aren't printing one yourself. Use `println()`. This is all documented. – user207421 May 26 '23 at 01:00
  • But when I execute `ls`, it outputs all contents in the same line, not with line terminators in between – Gabriel Bergoc May 28 '23 at 15:18
  • 1
    try to execute `ls > sample` and check the format inside `sample`; or `ls | more` (terminal output is formatted differently) ... searching a bit more, from `info ls`: "*... If standard output is a terminal, the output is in columns (sorted vertically) and control characters are output as question marks; otherwise, the output is listed one per line and control characters are output as-is. ...*" – user16320675 May 28 '23 at 20:50
  • 1
    use `ls -C` if you need the output in columns. Anyway you will probably still *want* to use `println` instead of `print` – user16320675 May 28 '23 at 20:53

1 Answers1

0

The reason this is happening is because you're using the print method.

To place a new-line delimiter after the value, use the println method.

Here is an example using print.

System.out.print("a");
System.out.print("b");
System.out.print("c");

Output

abc

And here is an example using println.

System.out.println("a");
System.out.println("b");
System.out.println("c");

Output

a
b
c

Reilas
  • 3,297
  • 2
  • 4
  • 17
  • But why is each character in a different line? If when I execute `ls`, it outputs all contents in the same line? – Gabriel Bergoc May 28 '23 at 15:17
  • @GabrielBergoc, I see what you're saying, interesting. I recommend starting a debugging process; set a breakpoint on the `while` statement and view the contents _iStream_. Possibly, it is returning the components with _\r_ delimiters? I'm not sure. – Reilas May 28 '23 at 15:44