how to run a java executable jar in another java program

前端 未结 1 503
生来不讨喜
生来不讨喜 2020-12-10 07:59

I know this question has been asked before but those answers didn\'t provide me an answer.

I want to execute a exec jar file in my java program and get the output fr

相关标签:
1条回答
  • 2020-12-10 08:43

    This works For Me..

    public class JarRunner {
        public static void main(String[] args) {
            ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\JCcc.jar");
            pb.directory(new File("C:\\"));
            try {
                Process p = pb.start();
                LogStreamReader lsr = new LogStreamReader(p.getInputStream());
                Thread thread = new Thread(lsr, "LogStreamReader");
                thread.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    class LogStreamReader implements Runnable {
    
        private BufferedReader reader;
    
        public LogStreamReader(InputStream is) {
            this.reader = new BufferedReader(new InputStreamReader(is));
        }
    
        public void run() {
            try {
                String line = reader.readLine();
                while (line != null) {
                    System.out.println(line);
                    line = reader.readLine();
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    This is what the Docs says-

    ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
    

    You can pass any number of arguments in constructor.

    Read more about process builder here.

    0 讨论(0)
提交回复
热议问题