简体   繁体   中英

Unable to run and give input to C code through Java

I want to run a C code through Java to print an integer which is entered by the user. I'm using ProcessBuilder class.

The Java code gives the same output (stdout:0) for every integer that I input through outputstream .

public class test {
    public static void main(String args[]) throws IOException {
        String line;
        ProcessBuilder builder = new ProcessBuilder("first1.exe");
        Process process = builder.start();
        OutputStream stdin = process.getOutputStream();
        InputStream stdout = process.getInputStream();
        InputStream err=process.getErrorStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
        writer.write(8);
        writer.flush();
        line = reader.readLine();
        System.out.println("Stdout: " + line);
    }
}

I always get the output:

stdout:0

The C code for first1.exe is:

#include <stdio.h>
int main ()
{
    int n;
    scanf("%d",&n);
    printf("%d",n);
    return 0;
}

In the above code when the C code first1.exe executes, it waits for an input to be given.

Here the writer just writes 8 and does nothing while the code first1.exe requires the user to write 8 and press enter.

The above code does not work because enter or newline is not given. Replacing the line writer.write(8); with writer.write(8+"\\n"); and add process.waitFor() before writer.write(8+"\\n") and it will work properly.

On replacing the statement, the code gives stdout:8 as output.

use

process.waitFor();
writer.write(8+"\n");
enter code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM