Search code examples
javaprocessruntime.execprocessbuilder

Java Runtime.exec() removes newlines from arguments


I have a Java class that is using Runtime.exec() to execute a cscript process with one String of several arguments that is retrieved from a database. One of these arguments includes newline characters that need to be preserved, but Runtime.exec() removes the newline characters. The problem doesn't exist when using ProcessBuilder, but I'd rather not have to worry about parsing my list of arguments.

Is there a way to preserve the newlines when calling exec()?

In case anyone wants to see it, here's a simplified example of the call to exec():

Process proc = Runtime.getRuntime().exec("cscript test.vbs \"line1\r\nline2\"");

My script was getting "line1 line2" as one argument with the newline replaced by a space.


Solution

  • There is little information in your question but I'm wildly guessing that your issue is as follows.

    Note that the forms of Runtime.exec(...) with a String command argument will end up using a StringTokenizer to generate the actual command tokens, which might explain the unexpected removal of newline characters. Try using a form of Runtime.exec(...) with a String array command argument so that no parsing of the string command arguments occurs.

    Of course, doing so might require you to parse the arguments yourself but that might be the only way to ensure that the program does what you expect.