简体   繁体   中英

Give inputs to Java program, which is running using RunTime.exec() on ubuntu

I have a java snippet in a file User.java

public class User{
  public static void main(String d[]){
    try{
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String name = br.readLine();
      System.out.println("Hello "+name);
    }catch(IOException e){
      e.printStackTrace();
    }
  }
}

Next, I have written another java program which runs above program, and its main function content is below.

Runtime runtime = Runtime.getRuntime();
Process proc1 = runtime.exec("javac MY_PATH/User.java");
Process proc2 = runtime.exec("java -cp MY_PATH User");

This code is working for all java snippets except which needs input. How should I give input for readLine(); methods.

Use Process.getOutputStream() and write your input data there.

OutputStream out = proc2.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write("World");
writer.flush();

You should use the Process.getOutputStream() method. Any data passed to this output stream will be passed to the standard input stream read by your User.java main method.

Do not forget to write a \\n character for the br.readLine(); to detect end of line.

Thought the above answers are write, I would like to produce the code for coming users :) The below method will accept all set of inputs(if we read more than one input for other programs) and writes them to bufferedWriter.

public static void giveInputToProcess(Process process, String[] inputs) {
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
            process.getOutputStream()));
    for (String input : inputs) {
        try {
            bw.write(input);
            bw.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM