Executing a different Jar file from another java program

后端 未结 2 1238
感情败类
感情败类 2020-12-20 10:41

As a part of my program, I have a connections manager that receives a connection from a client, and then gives the client a port number and a password to use to connect. A

相关标签:
2条回答
  • 2020-12-20 10:55

    I have suceessfully tested the scenario and I can execute the jar file with in java programme (without setting the classpath).

    Can you make sure that you have added Manifest file in the jar which has Main-Class attribute.

    My steps and output:

    1. Created Mainfest file with the following line: Main-Class: com.test.TestJSSJar
    2. Created Test Java program:

    package com.test;

    public class TestJSSJar extends Object {
    
        public static void main(String args[]) {
            System.out.println("Hi! I'm in the jar");
            System.out.println("Arg:" + args[0]);
        }
    }
    

    3.Package the jar (moved to temp folder): jar cvfm jss.jar manifest.txt com

    4.Write test program:

    import java.io.BufferedInputStream;
    import java.io.IOException;
    
    public class TestJSS extends Object {
    
        static int i = 0;
    
        public static void main(String args[]) throws IOException, InterruptedException {
            System.out.println("Calling jar");
            Process p = Runtime.getRuntime().exec("java -jar /temp/jss.jar arg1 arg2");
            BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
            synchronized (p) {
                p.waitFor();
            }
            System.out.println(p.exitValue());
            int b=0;
            while((b=bis.read()) >0){
    
                System.out.print((char)b);    
            }        
            System.out.println("");
            System.out.println("Called jar");
        }
    }
    

    5.Output

    Calling jar
    0
    Hi! I'm in the jar
    Arg:arg1
    
    Called jar
    
    0 讨论(0)
  • 2020-12-20 11:04

    Include jar in the classpath and call the main method of the Main-class of the jar from your main.

    Suppose Main-class of CytoscapeInterface.jar is JarMain.class (You can look it up in META-INF of CytoscapeInterface.jar), then from your program, call it like this:

    JarMain.main(new String[]{"arg1", "arg2"});
    

    You can also call it from a new Thread so that you can continue with your program.

            new Thread(
            new Runnable() {
                public void run() {
                    try {
                        JarMain.main(new String[]{"arg1", "arg2"});
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    
    0 讨论(0)
提交回复
热议问题