Kaushali de silva
Kaushali de silva

Reputation: 70

call to C program with command line argument from java

I want to pass the parameters from my java program to C program which is execute as command line argument. This is my C program,

    #include <stdio.h>

int main( int argc, char *argv[] )  {

   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
}

This is output I got when I compiled it from terminal.

lclab@lclab:~/Desktop/jni$ ./a.out param1
The argument supplied is param1

I want to pass parameters(param1) to this program from my java program. How can I do that? I tried with java process builder but it always return -1.

try {
                ProcessBuilder processBuilder =
                        new ProcessBuilder("gcc", "/home/lclab/Desktop/jni/test.c", "param1");
                Process proc = processBuilder.start();
                System.out.println(proc.getInputStream().read());
                return proc.getInputStream().read();
            } catch (IOException e) {
                e.printStackTrace();
                return 99;
            }

My machine is ubuntu.

Upvotes: 0

Views: 644

Answers (1)

kocica
kocica

Reputation: 6465

Compile C source code, you will have executable file.

g++ test.c -o test

Change this line

new ProcessBuilder("gcc", "/home/lclab/Desktop/jni/test.c", "param1");

Paste executable filename instead of test.c

new ProcessBuilder("gcc", "/home/lclab/Desktop/jni/test", "param1");

Or use Java native interface

EDIT:

public static void CompileCprog(String filename){

        File dir = new File("C://Users//JohnDoe//workspace//Project");

        try {  
            String exeName = filename.substring(0, filename.length() - 2);
            Process p = Runtime.getRuntime().exec("cmd /C gcc " + filename + " -o " + exeName, null, dir);  
            Process p = Runtime.getRuntime().exec("cmd /C dir", null, dir);  
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));  
            String line = null;  
            while ((line = in.readLine()) != null) {  
                System.out.println(line);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }   
    }

Upvotes: 2

Related Questions