Search code examples
javainputstreambufferedreaderoutputstreamprocessbuilder

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.


Solution

  • 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).