使用gcc通过javacode编译C源代码

时间:2016-03-09 19:22:43

标签: java c gcc compilation

我正在尝试使用exec方法

通过java代码编译c文件
String inputFilePath = "\"D:\\Soft\\WebApplication\\build\\web\\code\\Demo.c\"";
String[] commands = {"cmd", "/c", "gcc",inputFilePath,"-o","Demo"};
Process p=Runtime.getRuntime().exec(commands);
DataInputStream din=new DataInputStream(p.getErrorStream());
String s="",temp;
while((temp=din.readLine())!=null)
      s+=temp;
      if(s.equals("")){
         cf.setResult("No Syntax Error");
      }
      else
        cf.setResult(s);

但它没有生成demo.exe文件

1 个答案:

答案 0 :(得分:0)

使用ProcessBuilder可以更轻松。

这应该适用于Windows(此刻,我这里只有Linux)。

String directory = "D:\\Soft\\WebApplication\\build\\web\\code\\";
String[] commands = {"cmd", "/C", "gcc", "Demo.c", "-o", "Demo.exe"};

ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(directory));
pb.command(commands);

Process p = pb.start();

// process in/out streams