简体   繁体   中英

Using dynamic path in Javas Runtime.exec()

I have written a Java application which is now compiled into a jar. Inside the applications main method I want to have the following:

Runtime.exec("java -jar myapp.jar arg1 arg2"))

(Or with Processbuilder if it's better)

Ie the application should fork itself and create new processes.

So far, so good... my problem is now that I think that I cannot just call "java" but I have to give the full path to the java directory and I also think that I have to give the full path to myapp.jar.

Is there a way to avoid hardcoding the full path? Ie that the java path and the path to myapp.jar is inferred at runtime inside the Runtime.exec?

Moreover, is it possible that the application can infer its name at runtime? Ie the applications name is myapp.jar but I don't want to hardcode it in the Runtime.exec(...).

Edit: I need it on Ubuntu but also running in Windows.

Option 1

Use Runtime.getRuntime().exec :

Process proc = Runtime.getRuntime().exec(new String[] {"java","-jar","myapp.jar","arg1","arg2"});

Doing getRuntime() should infer where the Java executable should be.

Option 2

Use ProcessBuilder :

ProcessBuilder pb = new ProcessBuilder("java","-jar","myapp.jar","arg1","arg2");
Process p = pb.start();

As noted in the documentation about the environment: The initial value is a copy of the environment of the current process (see System.getenv() ).

Option 3

Load the file into your classpath and then call the main method directly:

File file = new File("/path/to/myapp.jar");    
JarFile jarFile = new JarFile(file);  
Manifest manifest = jarFile.getManifest();
if (manifest != null) {
    Attributes attributes = manifest.getMainAttributes();  
    String className = attributes.getValue(Attributes.Name.MAIN_CLASS);
    URLClassLoader loader = new URLClassLoader(new URL[] { file.toURI().toURL() }); 
    Class<?> cls = loader.loadClass(className);
    Method main = cls.getDeclaredMethod("main", String[].class);  
    String[] args = {"arg1", "arg2"};  
    main.invoke(null, args); // static methods are invoked with null as first argument
} else {
    System.err.println("Cannot run " + file);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM