How to run a .jar file from inside another java program?

前端 未结 4 818
时光说笑
时光说笑 2021-01-22 04:44

i have a .jar file, which I can run on the command line:

java -jar myFile.jar argument1

I want to save the output of this .jar as a String vari

4条回答
  •  -上瘾入骨i
    2021-01-22 05:37

    I

    Running Jar file require you to have the jar file included in your class path. This can be done at run time using URLClassLoader. Simply construct a URLClassLoader with the jar as one of the URL. Then call its forClass(...) if you know the class name (full name of course). Or inspect the manifest file using its 'findResources(String name)'.

    Once you get the class, you can use reflection to get its static method main.

    Seeing your question again, you know the class name, so if you are sure the jar file in already in the class path, then you can just call it as you tried.

    II

    To capture the output, you can call System.setOut(PrintStream out) and System.setErrPrintStream out) to change the print stream. You can pass the printstream that you create. Like this:

    ByteArrayOutputStream BAOS = new ByteArrayOutputStream();
    PrintStream MyOut = new PrintStream(BAOS);
    System.setOut(MyOut);
    
    // Do something to have something printed out.
    ...
    
    String TheCaptured = new String(BAOS.toByteArray());

    Hope this helps.

提交回复
热议问题