Search code examples
javaprocessbuilder

Java ProcessBuilder() runs a program, but the program doesn't return any output


I run the program like this:

    Process process;
    try {
        process = new ProcessBuilder("java", "-jar", "test.jar", "1", "20").start();
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
          System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The program I call uses standard output System.out.println("Hello!"); However, the the calling program gets nothing back. Am I using ProcessBuilder() wrong? Thanks!


Solution

  • If there is no constraint to start another JVM (for example: usage of System.exit() in test.jar) you could load and run the test.jar inside the current JVM.

    Following snippet shows the principle.

    File file = new File("/tmp/test.jar");
    URLClassLoader loader = new URLClassLoader(
            new URL[]{file.toURI().toURL()}
    );
    
    String className = new JarFile(file)
            .getManifest()
            .getMainAttributes()
            .getValue(Attributes.Name.MAIN_CLASS);
    
    Method main = loader
            .loadClass(className)
            .getDeclaredMethod("main", String[].class);
    
    Object arg = new String[]{"1", "20"};
    
    try {
        main.invoke(null, arg);
    } catch (Exception e) {
        // do appropriate exception handling here
        e.printStackTrace(System.err);
    }