I want to launch a Java jar by Runtime but Windows is making problems again. I know this must have come up hundreds of times but I tried a few things (like String.replace("/","\")) and since I cannot debug on Windows this is taking quiet some time. This works fine under Unix:
public boolean run(String args[], String workingDir, boolean output) throws
FileNotFoundException {
if (args.length <= 0) {
System.err.println("No cmd provided");
}
if (workingDir == null) {
workingDir = "./";
}
ProcessBuilder pb = new ProcessBuilder(args);
pb.directory(new File(workingDir));
Process p;
int exitValue = 0;
try {
p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
p.waitFor();
if (output) {
while ((line = br.readLine()) != null) {
setChanged();
notifyObservers(line);
}
}
exitValue = p.exitValue();
} catch (InterruptedException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (exitValue == 0) {
return true;
} else {
开发者_开发技巧 throw new FileNotFoundException();
}
}
launched by:
public static void launchApp(String subPath) throws FileNotFoundException {
String[] args = String.format("java -jar -Xdock:name=AppName -Xdock:icon=%sicon.icns %AppName.jar", subPath, subPath).split(" ");
ExecRuntime.run(args, null);
}
Use the standard java system properties when doing platform specific things in Java to ensure that your application is portable. See System Properties for more information on some of the values available to your app.
After taking the code appart, I found the 2 errors: 1. My OS method used String.replaceAll("/","\") and threw a StringIndexOutOfBoundsException (don't know why) but String.replac() works fine 2. I was naiv enough to think that the VM would ignore unsupported parameters like -Xdock:name and -Xdock:icon but it does not, so I made a seperate exec String for Mac. Thanks for your hints and help!
精彩评论