2

I want to write a program which executes JARs and gets their output. When the JAR program has only a print statement it works fine, but when it asks for input during execution, the program freezes.

Code of the JAR file program:

import java.util.*;

public class demo {

    public static void main(String r[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Hello ...");
        System.out.println("please enter the number :");
        int i = sc.nextInt();
        System.out.println(" number : " + i);

    }
}

Code of the original program which runs the JAR files:

public class jartorun {
    public static void main(String arg[]) throws IOException {
        String t = "javaw -jar D:\\jarcheck\\temp.jar";
        Process p = Runtime.getRuntime().exec(t);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        while ((line = input.readLine()) != null) {
            System.out.print(line + "\n");
        }
        input.close();
    }
}

I can give input to the JAR using process.getOutputStream(), but how would I use it so I can create a program which can give input to a JAR and read its output simultaneously?

Makoto
  • 104,088
  • 27
  • 192
  • 230
Dhaval
  • 43
  • 5
  • Why are you running a `jar` from Java? Why not load it into the classpath and simply invoke the method? Further, if you do choose to run external programs from Java, use the new [`ProcessBuilder`](http://stackoverflow.com/questions/6856028/difference-between-processbuilder-and-runtime-exec) rather than `Runtime.exec`. – Boris the Spider Apr 23 '15 at 13:11

2 Answers2

0

You can use p.getOutputStream() to provide input to the launched process.

Petr
  • 5,999
  • 2
  • 19
  • 25
0

If you want to run stuff outside the VM use the ProcessBuilder. Works fine for me and you can inherit the IO Stream.

ProcessBuilder builder = new ProcessBuilder("./script.sh",
                            "parameter1");
            builder.directory(new File("/home/user/scripts/"));
            builder.inheritIO();

            try {
                    Process p = builder.start();
                    p.waitFor();
                    // Wait for to finish
            } catch (InterruptedException e) {
                    e.printStackTrace();
            } catch (IOException ioe) {
                    ioe.printStackTrace();
            }

This should also work with Windows batch scripts and paths. (haven't tried the input though)

Liebertee
  • 88
  • 9