2014-11-03 37 views
1

我想使我的項目中的任何文件都可以被任何用戶讀取,因爲他們不會擁有和我一樣的目錄。如何讀取項目內的文件txt?

所以我有這樣的:

String filme = "somefile.txt" 

String datastr = ""; 
    reader = new BufferedReader(new FileReader("C:/Path"+filename)); 
    String line = reader.readLine(); 
    while(line != null) { 
     datastr += line + "\n"; 
     line = reader.readLine(); 
    } 

任何幫助,將不勝感激。在此先感謝

+2

http://stackoverflow.com/questions/2914375/getting-file-path-in-java – nem035 2014-11-03 21:18:11

回答

0

只是要簡單,ClassLoader是答案:

 
ClassLoader cl = Thread.currentThread().getContextClassLoader(); 
URL rsc = cl.getResource("MyFile.txt"); 
File f = new File(rsc.getPath()); 

但這裏有關於這個問題hereherehere只是爲了快速搜索更多的答案。使用搜索! ;-)

+0

所以我這樣做是這樣的... String datastr =「」; \t ClassLoader cl = Thread.currentThread()。getContextClassLoader(); \t URL rsc = cl.getResource(file); \t FileReader f = new FileReader(rsc.getPath()); \t reader = new BufferedReader(f); \t \t String line = reader.readLine(); \t \t while(line!= null){ \t \t \t datastr + = line +「\ n」; \t \t \t line = reader.readLine(); \t \t} 並收到java.lang.NullPointerException ... – pMpC 2014-11-03 21:40:12

+0

@pmpc使用調試器找出在哪個步驟中獲得NPE。和你的'文件'變量是什麼? – 1ac0 2014-11-04 07:34:22