Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Values in to C variables that is running from Java Code

Tags:

java

c

input

I have successfully executed the C Code from Java Code, But I have a question regarding, I want to read values into the C variables where C Program is running from Java Code . How to do that?

My C Code will be as follows.

int main()
{ 
    int op;
    printf("\n Hello World... ");
    printf("\n Enter any value : ");
    scanf("%d",&op);
    printf("\n The value entered is : %d",op);
    getch();
    return 0;
}

and my java code is as follows.

import java.io.*;
public class Test {
   public static void main(String args[]) {
      try {
            String s = " ";
            Process processCompile = Runtime.getRuntime().exec("e:/Sample.exe");

            BufferedReader stdInput = new BufferedReader(new
            InputStreamReader(processCompile .getInputStream()));
            // read the output from the command
            System.out.println("EXE OUTPUT");
            while ((s = stdInput.readLine()) != null) {
               System.out.println(s);
           }
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

So, what modifications i have to do in the java code, so that i can input values to C variables. Thanks in Advance

like image 759
Sankar Avatar asked Oct 05 '22 02:10

Sankar


1 Answers

You need to use JNI, not ProcessBuilder. Or you need to write those values into a file and read the file from C. Or you need to write those values into the process input stream. Which, to confuse you, is called 'outputStream'.

Something like:

OutputStreamWriter osw = new OutputStreamWriter(process.getOutputStream(), "utf-8");
osw.append(String.format("value1=%d value2=%d", value1, value2));
osw.flush();

and then in C read that string from stdin.

like image 163
bmargulies Avatar answered Oct 12 '22 23:10

bmargulies