g ++不适用于Java

时间:2016-07-30 11:04:02

标签: java processbuilder

我正在编写用于编译程序的Java代码。

因此用户可以选择要编译的文件,然后程序通过自己的g ++运行。

在网上看,特别是StackOverFlow,我决定使用这段代码:

//Set a FileChoose called fc, got the file path (filePath) and the directory path (dirPath), then:
ProcessBuilder process=null;
try {
    process = new ProcessBuilder("g++", filePath, " -o "+dirPath+"/a.out").start();
} catch (IOException ex) {
    System.err.println("Error compiling file");
    Logger.getLogger(Nuovo.class.getName()).log(Level.SEVERE, null, ex);
    System.exit(0);
}

重点是它不会返回任何错误,当我检查文件是否已编译时,它就没有了。

有什么想法吗?

非常感谢!

2 个答案:

答案 0 :(得分:3)

我建议你阅读程序的输出,看看它产生了什么错误。

我的猜测是会说类似的东西。

File not found:  -o dir/a.out

注意,您已指定" -o "+dirPath+"/a.out"是单个参数。这就像写作

g++ $filePath ' -o dir/a.out'

也许你想要的是

new ProcessBuilder("g++", filePath, "-o", dirPath+"/a.out").start();

为什么Java不像shell那样解析你的论点?因为它将参数传递给系统调用exec所以它实际上没有做任何C ++不会做的事情。

答案 1 :(得分:0)

您应该使用位于https://commons.apache.org/proper/commons-exec/download_exec.cgi的apache commons exec库。 java进程exec几乎没有什么主要的空白:如果本机命令发送消息,java进程将不会解析消息,也会阻止java程序的执行。

示例:

  • 您从java调用以下命令:del
  • 系统会向您发回确认消息:您确定(是/否)?
  • java ProcessBuilder不会解析确认消息,它会阻止程序的执行。

出于这个原因,我推荐apache commons exec library,它也有一个很好的文档https://commons.apache.org/proper/commons-exec/tutorial.html