user994165 user994165 - 4 years ago 851
Java Question

Java Runtime.exec()

I can run this command from the command line without any problem (the validation script executes):

c:/Python27/python ../feedvalidator/feedvalidator/src/

and from java if I leave off the URL parameter and just do:

String[] args1 = {"c:/Python27/python", "../feedvalidator/feedvalidator/src/" };
Runtime r = Runtime.getRuntime();
Process p = r.exec(args1);

it works fine. If I use certain URLs for a parameter such as:

String[] args1 = {"c:/Python27/python", "../feedvalidator/feedvalidator/src/" , ""};
// or
String[] args1 = {"c:/Python27/python", "../feedvalidator/feedvalidator/src/" , ""};

it also works fine.

But if I use this particular URL, then the script just hangs (java waits for the process to finish). I’m not sure why it works from the command line for that URL but not from a java program. I tried adding quotes to surround the URL parameter but that didn’t work either. I don’t see any character in the URL that I think need to be escaped.

Full Code:

String urlToValidate = "";

String[] args1 = {"c:/Python27/python", "C:/Documents and Settings/vhaiswcaldej/DAS_Workspace/feedvalidator/feedvalidator/src/", urlToValidate };
System.out.println(args1[0] + " " + args1[1] + " " + args1[2]);

Runtime r = Runtime.getRuntime();
Process p = r.exec(args1);
BufferedReader br = new BufferedReader(new InputStreamReader(
int returnCode = p.waitFor();
System.out.println("Python Script or OS Return Code: " + Integer.toString(returnCode));
if (returnCode >= 2) {
.out.println("OS Error: Unable to Find File or other OS error.");

String line = "";
while (br.ready()) {
String str = br.readLine();
if (str.startsWith("line")) {
//TODO: Report this error back to test tool.

Answer Source

You need to drain the output and error streams of the process, or else it will block when the executed program produces output.

From the Process documentation:

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download