2016-07-30 60 views
0

我正在研究用於編譯程序的Java代碼。g ++不能與Java一起工作

所以用戶可以選擇要編譯的文件,然後程序運行自己的g ++。

找上了網,尤其是計算器,我已經決定要使用此代碼:

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

的一點是,它不返回任何錯誤,當我檢查,如果該文件編譯沒有什麼。

有什麼想法?

非常感謝!

+3

閱讀您的過程的錯誤流,以獲取更多信息 – Jens

+5

此代碼不編譯。 'ProcessBuilder.start()'返回一個'Process',但是你把它賦給一個變量'ProcessBuilder'。 –

+0

對不起之前沒有回覆,我一直有點忙。 問題是沒有任何錯誤。 正如@JornVernee所說的問題是我正在將一個Process返回給ProcessBuilder。我通過這種方式解決了這個問題:Process pr; 運行時rt = Runtime.getRuntime(); try { pr = rt。exec(String []);如果exec()函數的參數是一個包含某些東西(取決於需要)的字符串數組,如{「bin/bash」,「-c」,comand} – icosac

回答

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的行爲像一個貝殼和分析你的論點?因爲它將參數傳遞給系統調用exec,因此它不會執行任何C++不會執行的操作。

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庫,它也有一個很好的文檔https://commons.apache.org/proper/commons-exec/tutorial.html