2013-02-13 49 views
2

所以我遇到了javax.tools.JavaCompiler的api和cmd行編譯器(這些都是同樣的事情!)之間的一個惱人的小問題。我只想使用一個參數到javac,如:* -d C:\ compiled \ C:\ programs \ HelloWorld.java *。這在cmd提示符下工作良好,但是我的代碼失敗,說該文件不存在。javax.tools.JavaCompiler「arguments」arg

public class Test { 

    private static String programsDir = "C:\\programs\\"; 
    private static String compiledDir = "C:\\compiled\\"; 
    private static String fileName = "HelloWorld.java"; 

    public static void main(String[] args){ 

     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 

     String arguments = "-d " + compiledDir + " " + programsDir + fileName ; 
     compiler.run(System.in, System.out, System.err, arguments); 
    } 

輸出是:

javac: file not found: -d C:\compiled\ C:\programs\HelloWorld.java 
Usage: javac <options> <source files> 
use -help for a list of possible options 

但我可以剪切和粘貼 「-d C:\編譯\ C:\程序\ HelloWorld.java」 到javac中。即,javac -d C:\ compiled \ C:\ Program Files \ HelloWorld.java的作品。

+0

'C:programs' - >''\''失蹤出於某種原因(你的代碼顯示了它的存在)? – nhahtdh 2013-02-13 07:09:40

+0

@nhahtdh雖然它是在代碼中 - 不知道是哪個使用;-) – assylias 2013-02-13 07:11:14

+0

對不起,你們是一個錯字。修復。 – Matt 2013-02-13 07:13:40

回答

2

run預計args來的列表,你嘗試過:

String[] args = {"-d", compiledDir, programsDir + fileName}; 
compiler.run(System.in, System.out, System.err, args); 
+1

我認爲'-d'應該是一個獨立的參數(假設'run'需要一個參數列表 - 以前從未使用過這個參數)。 – nhahtdh 2013-02-13 07:14:12

+0

謝謝assylias。這很有效,但在「-d」後的d後面不能有空格,因爲它不會識別該標誌。 – Matt 2013-02-13 07:20:54

+0

@ Matt8541修正 - 從來沒有用過這種方式說實話。 – assylias 2013-02-13 07:21:35