I am using the following program (taken from an issue of the Core Java tech tips) to run a native command/app and display its output to standard out:
the strange problem that I am running into is that when I use the above program to run the "ipconfig" command on Windows XP, the output from ipconfig has extra lines in it.
This is immediately obvious if I run the ipconfig command separately myself in a command prompt window. What's stranger yet is that it only appears to be happening with the "ipconfig" command/app. If I run any other Windows command using DoRuntime, the output from the command execution is OK and there are no extra lines in it.
Any ideas on why I am getting extra newlines when running ipconfig using Runtime.exec() or ProcessBuilder?
It is strange, indeed. It seems to me that the difference is coming in from the ipconfig side of things - perhaps it defines a new line in a funky way, which is getting translated to two lines in Java. You might be able to clean it up by using a Scanner and supplying a regex for splitting tokens or something... not sure.
Scanner code like this works fine for ipconfig and other commands (help for example):
If I changed the delimiter to just "\\n" it woks fine as well. If you change it to "\\r" then the Scanner misbehaves by adding the extra line in all cases (not just in ipconfig). Finally, changing the delimiter to "\\r\\r" makes it behave just like the BufferedReader -> ipconfig has extra lines but other commands don't.
More probing ... In my case when I use the scanner with the \\r\\r delimiter using commands other than ipconfig it reads the entire input at once, and prints out all the contents as if it were one line red from the input stream. It appears in the output as multiple lines because it has proper new line entries in the middle of the content. For the ipconfig, command, though, each line is read individually.
What I think is happening is the ipconfig ends each line with "\\n\\r\\r", and the buffered reader will use any of "\\n", "\\n\\r", or "\\r" as line delimiters. So it sees "\\n\\r\\r" and sees two delimiters - "\\n\\r" and "\\r", giving you two lines.
You are absolutely correct... I modified DoRuntime.java so that it instead printed out char values from the program's output and I can indeed see that for whatever reason ipconfig is delimiting lines in its output using "<CR><CR><LF>"!
Thanks for pointing out the use of Scanner to correctly parse the lines.