Search code examples
javajarprocessbuilder

How to give jar file output back to ProcessBuilder?


I am executing a simple jar file by using process builder. The jar file simply computes the square of a number by asking the user to enter a number. I can enter a number at console but the program hangs. How can I pass this (number) back to process builder for its square to be computed by the jar file?

Here is my code for this:

public static void executeSystemCommand(String... args) {
try {
    ProcessBuilder pb = new ProcessBuilder(args);

    pb.redirectErrorStream(true);           
    Process proc = pb.start();
    Reader reader = new InputStreamReader(proc.getInputStream());

    int ch;
    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);    
    }

    reader.close();
    Scanner scan = new Scanner(System.in);

    int k = scan.nextInt();
    proc.getOutputStream().write(k);
    proc.getOutputStream().close();

    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);    
    }

    reader.close();
} catch (IOException e) {
    e.printStackTrace();
    System.exit(-1);
}
}

Solution

  • Here is a code that inputs a string b to the jar file and returns an arraylist of booleans on the basis of output received from the jar file.

    public ArrayList<Boolean> pro(String b) throws IOException, Exception {
            ArrayList<Boolean> ar = new ArrayList<Boolean>();
            try {
                ProcessBuilder pb = new ProcessBuilder("java", "-jar",
                        "myjar.jar");
    
                pb.directory(new File("path to myjar"));
                Process proc = pb.start();
    
                Scanner in = new Scanner(proc.getInputStream());
                PrintWriter out = new PrintWriter(proc.getOutputStream());
    
                // Read user input
                out.println(b);
                out.flush();
                String response = new String();
    
                // Read the response
                for (int i = 0; i < b.length(); i++)
                    response = in.nextLine();
    
                in.close();
                out.close();
    
                StringTokenizer st = new StringTokenizer(response);
                while (st.hasMoreTokens()) {
                    String bol = st.nextToken();
    
                    if (bol.equals("true"))
                        ar.add(true);
                    else
                        ar.add(false);
    
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ar;
        }