问题
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.
回答1:
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
).
回答2:
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);
}
来源:https://stackoverflow.com/questions/50432304/using-inputstream-and-outputstream-to-read-and-write-data-to-a-process