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

泄露秘密 提交于 2020-01-05 23:45:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!