【问题标题】:call to C program with command line argument from java使用 java 的命令行参数调用 C 程序
【发布时间】:2017-08-09 17:15:42
【问题描述】:

我想将参数从我的 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

我想将参数(param1)从我的 java 程序传递给这个程序。我怎样才能做到这一点?我尝试使用 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。

【问题讨论】:

  • 你需要先编译你的C程序,然后运行生成的可执行文件。

标签: java c command-line-arguments


【解决方案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();  
        }   
    }

【讨论】:

  • 非常感谢您的快速回答。我已经执行了 C 程序。并改变了线路。但它仍然返回 -1
  • 尝试执行你的可执行文件,转到/home/lclab/Desktop/jni,在此处打开终端并写./test param1,运行是否正确?
  • 是的,它正在执行。 lclab@lclab:~/Desktop/jni$ g++ test.c -o test lclab@lclab:~/Desktop/jni$ ./test param1 提供的参数是param1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 2013-01-27
相关资源
最近更新 更多