This week's book giveaways are in the Cloud and AI/ML forums. We're giving away four copies each of Cloud Native Patterns and Natural Language Processing and have the authors on-line! See this thread and this one for details.
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.
for the ipconfig. Anyway, it seems like this Scanner would work for ipconfig and otherwise
When I do this, then it reads each line individually for both ipconfig and other commands like help properly. It is looking for 0 or more Carriage Returns (\r) followed by a New Line (\n).
posted 9 years ago
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.