天道酬勤,学无止境

Using inputStream and OutputStream to read and write data to a process

I am currently running a .class file as a process. The .class file is a simple program that asks the user to input a number, takes the input and prints the user's input back to the screen. Up to now, i have managed to print the "Enter a number: " statement from the process on the console through InputStream and write the input entered by the user through OutputStream. I am unable to print the last statements on the screen, which should be

"You entered : " + userinput

My code is:

String command [] = {"java" , "-cp", "C:\\Users\\Mahika\\Documents\\NetBeansProjects\\JavaTest\\compilerTest", "InputInteger"};
ProcessBuilder pb = new ProcessBuilder(command);
Process p = pb.start();
System.out.println("Process started");
BufferedReader br = new BufferedReader (new InputStreamReader(p.getInputStream()));
String output = null;

while((output = br.readLine()) != null){
    System.out.println(output);
    break;
}
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

OutputStream os = p.getOutputStream();
PrintStream ps = new PrintStream(os);
os.write(i);
os.flush();  

I don't know how to use InputStream again to read the "You entered:" + userinput.

评论

This should work:

public static void main(String[] args) throws IOException {
    String command[] = {"java.exe", "-cp", "C:\\Users\\Mahika\\Documents\\NetBeansProjects\\JavaTest\\compilerTest", "InputInteger"};
    ProcessBuilder pb = new ProcessBuilder(command);
    Process p = pb.start();
    System.out.println("Process started");
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    System.out.println(br.readLine());
    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    PrintStream ps = new PrintStream(p.getOutputStream(), true);
    ps.println(i);
    System.out.println(br.readLine());
}

Just make sure that input prompt in InputInteger class is finished by a newline character (e.g. created by println and not print).

I am not really sure to understand your problem but as far as I can see, you should only use the scanner to wait for the user to type his text, something like this:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    System.out.println("you entered: " + i);
}

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐