2015-07-03 65 views
1

當我試着在我的代碼加載了一個.txt文件使用.txt文件時,我得到這個錯誤:爪哇 - 在錯誤的.jar

java.io.FileNotFoundException: file:\C:\Users\Me\Desktop\Program.jar!\test\foo.txt (The filename, directory name, or volume label syntax is incorrect) 

我加載這些文件的代碼是這樣的:

try { 
     String path = getClass().getResource(file).getPath(); 
     BufferedReader reader = new BufferedReader(new FileReader(path)); 
     ... 
    } catch(IOException e) { 
     System.err.println("Could not read file!"); 
     e.printStackTrace(); 
     System.exit(-1); 
    } 

我加載到方法的字符串是這樣的:

foo.txt 

即使我檢查了很多次,該文件存在在精確的路徑,但米y程序仍然無法找到它。爲什麼Program.jar最後會有感嘆號?是不是重要?

非常感謝任何幫助回答我的問題的人。

回答

1

如果您在控制檯中使用jar啓動它,您最好以InputStream的身份訪問您的資源並按照需要的方式處理它。當你輸入實際的路徑時(尤其是不相對的) - 你試圖去到INSIDE這個jar文件,這是錯誤的。

這裏的接近(僞)代碼,您的問題:

InputStream resource = ClassName.class.getResourceAsStream("/test/foo.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(resource)); 
//do some stuff 
resource.close(); 
reader.close(); 

感嘆號是JVM使用要注意.jar文件路徑的分隔符。