Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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();

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();
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top