A trap of Runtime.getRuntime().exec
439 views. 2010-1-28 17:14
|Individual Classification:Tech|
Description: When you use Runtime.getRuntime().exec to implement a Java command line on various platforms, your codes may work well on Windows but failed on Linux. Exception "ClassNotFound" occurs.
Analysis: Sample is below(highlighted in red. I don't know why hasn't coding-style button here?):
package com.ibm.lotus.search.engine.test.cluster;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClusterRunner
{
...
public boolean startNode(NodeInfo nodeinfo)
throws IOException
{
NodeInfo nodeinfo1 = nodeinfo;
JVM INSTR monitorenter ;
...
String s = (new StringBuilder()).append("\"").append(System.getProperty("java.class.path")).append("\"").toString(); //problem codes highlighted by red Bold
String s1 = (new StringBuilder()).append("java -classpath ").append(s).append(" ").append(nodeinfo.getClassName()).append(" ").append(nodeinfo.getPortNumber()).append(" ").append(configFolderPath).toString();
...
Process process = Runtime.getRuntime().exec(s1);
...
Linux JRE, neither SUN or IBM support to use a pair of quota marks to enclose a Java classpath string, though it does make sense for Win.
Solution: so, perhaps you have to add some branches do handle these command string, for example:
if (File.seperator == '\') {
//codes for Win
}else{
//codes for *nix
}
(note: people can implements a Java command line which contained a classpath enclosed by quota marks on a Linux Shell prompt, just because the quota marks be implicitly trimmed by Shell)