Execute .jar file from a Java program

瘦欲@ 提交于 2019-11-26 15:14:31

I suggest you use a ProcessBuilder and start a new JVM.

Here is something to get you started:

ProcessBuilder pb = new ProcessBuilder("/path/to/java", "-jar", "your.jar");
pb.directory(new File("preferred/working/directory"));
Process p = pb.start();
    Process proc = Runtime.getRuntime().exec("java -jar Validate.jar");
    proc.waitFor();
    // Then retreive the process output
    InputStream in = proc.getInputStream();
    InputStream err = proc.getErrorStream();

    byte b[]=new byte[in.available()];
    in.read(b,0,b.length);
    System.out.println(new String(b));

    byte c[]=new byte[err.available()];
    err.read(c,0,c.length);
    System.out.println(new String(c));

Another way to do on windows is:

Runtime.getRuntime().exec("cmd /c start jarFile");

this way you can set priority of your process as well (normal/low/etc)

First, the description of your problem is a bit unclear. I don't understand if you want to load the classes from the jar file to use in your application or the jar contains a main file you want to run. I will assume it is the second.

If so, you have a lot of options here. The simplest one would be the following:

String filePath; //where your jar is located.
Runtime.exec(" java -jar " + filepath);

Voila... If you don't need to run the jar file but rather load the classes out of it, let me know.

You can run a jar file from where ever you want by using only this one line code.

    Desktop.getDesktop().open(new File("D:/FormsDesktop.jar"));

where

new File("your path to jar")

Hope it helps.

Thanks.

Иван Александров
  1. Add jar library to your project
  2. Import main class (see manifest in jar file)
  3. Invoke static method main with arguments

    String args[] = {"-emaple","value"};
    PortMapperStarter.main(args);
    

To run an executable jar from inside your java application, you can copy the JarClassLoader from https://docs.oracle.com/javase/tutorial/deployment/jar/examples/JarClassLoader.java

Use it like this. In this snippet, jarUrl is the URL to download the jar from, for example file:/tmp/my-jar.jar and args is the array of strings you want to pass as command line arguments to the jar.

JarClassLoader loader = new JarClassLoader(jarUrl);
String main = loader.getMainClassName();
loader.invokeClass(main, args);

Keep in mind that you're now inserting someone else's binary into your code. If it gets stuck in an infinite loop, your Thread hangs, if it calls System.exit(), your JVM exits.

1) Set the class path from environment variables

2) Go to the folder where your jar file exists

3) Run the following commands through command prompt

java -jar jarfilename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!