Running an unpainted command line from Java

I am currently using ProcessBuilder to run commands from a java server. This server should replace the old Perl server, and many of our legacy codes define platform-specific command lines.

For example, in windows, this can be done:

command -option "hello world" 

and on unix, this can do:

 command -option 'hello world' 

The problem is that ProcessBuilder and Runtime.exec accept in tokenized command lines (for example, {"command", "-option", "hello world"} for unix and windows).

While I prefer an independent platform, we have somewhere in the range of 30 million lines of perl code in our code base. Without me writing a tokenizer for different platforms (it doesn’t matter, I just don’t want to do WTF), is there a way to let the operating system shell tokenize the command line?

+1
source share
2 answers

Can you use an overloaded Runtime.exec (String) that takes one line and runs it as a whole command?


On Windows, the following works:

 Process p = Runtime.getRuntime().exec("perl -e \"print 5\""); System.out.println(IOUtils.toString(p.getInputStream())); p.destroy(); 

This is more or less what Runtime.exec (String) does:

 public static void main(String [] args) throws Exception { Process p = new ProcessBuilder(getCommand("perl -e \"print 5\"")).start(); System.out.println(IOUtils.toString(p.getInputStream())); p.destroy(); } private static String[] getCommand(String input) { StringTokenizer tokenizer = new StringTokenizer(input); String[] result = new String[tokenizer.countTokens()]; for (int i = 0; tokenizer.hasMoreTokens(); i++) { result[i] = tokenizer.nextToken(); } return result; } 
+7
source

I think the quotation marks are interpreted by the shell. Instead, put the command in a shell script:

 $ cat temp.sh #!/bin/sh perl -e "print 5" 

and execute it:

 import java.io.BufferedReader; import java.io.InputStreamReader; public class PBTest { public static void main(String[] args) { ProcessBuilder pb = new ProcessBuilder("./temp.sh"); pb.redirectErrorStream(true); try { Process p = pb.start(); String s; BufferedReader stdout = new BufferedReader ( new InputStreamReader(p.getInputStream())); while ((s = stdout.readLine()) != null) { System.out.println(s); } System.out.println("Exit value: " + p.waitFor()); p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close(); } catch (Exception ex) { ex.printStackTrace(); } } } 

Console:

 5 Exit value: 0 
+5
source

All Articles