使用java中的命令行参数调用C程序

时间:2017-08-09 08:49:03

标签: java c command-line-arguments

我想将参数从我的java程序传递给C程序,该程序作为命令行参数执行。这是我的C程序,

    #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");
   }
}

这是我从终端编译时得到的输出。

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

我想从我的java程序将参数(param1)传递给这个程序。我怎样才能做到这一点?我尝试使用java进程构建器,但它总是返回-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;
            }

我的机器是ubuntu。

1 个答案:

答案 0 :(得分:1)

编译C源代码,您将拥有可执行文件。

g++ test.c -o test

更改此行

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

粘贴可执行文件名而不是test.c

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

或使用Java native interface

编辑:

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();  
        }   
    }