2012-07-27 142 views
0

我有一個項目可以找到一個文本文件並將其轉換爲一個字符數組。但是,由於某種原因,它沒有找到該文件。這是所有的代碼,涉及開/讀取文件:Java項目找不到文件

public void initialize(){ 
    try{ 
    File file = new File(getClass().getResource("/worlds/world1.txt").toString()); 
    BufferedReader reader = new BufferedReader(
      new InputStreamReader(
       new FileInputStream(file), 
       Charset.forName("UTF-8"))); 
    int c; 
    for(int i = 0; (c = reader.read()) != -1; i ++) { 
     for(int x = 0; x < 20; x++){ 
      worlds[1][x][i] = (char) c; 
      c = reader.read(); 
     } 
    } 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 

} 

運行時,它顯示的是它指向正確的文件控制檯,但聲稱沒有存在那裏。我已經檢查過,並且該文件完整無缺。這裏可能會出現什麼問題?

+0

您應該使用'toURI()'而不是'toString()'。但是爲了更好的回答請看@Raffaele post – Xeon 2012-07-27 17:15:18

回答

3

你不應該得到這樣的資源。您可以使用

BufferedReader reader = new BufferedReader(new InputStreamReader(
    getClass().getResourceAsStream("/worlds/world1.txt") 
)); 

此外,當您打包應用程序,如果你開發它的IDE中要小心,否則你會爲嵌入式資源從包裝計算碰上共同CLASSPATH煩惱

0

文件路徑根文件夾。假設src文件夾根包的文件夾,應確保,即world1.txt文件位於src/worlds/文件夾和全路徑是src/worlds/world1.txt

第二點,使用以下代碼來獲取嵌入的文件讀取器對象:

// we do not need this line anymore 
// File file = new File(getClass().getResource("/worlds/world1.txt").toString()); 

// use this approach 
BufferedReader reader = new BufferedReader(
     new InputStreamReader(
      getClass().getResourceAsStream("/worlds/world1.txt"), 
      Charset.forName("UTF-8"))); 
0

你還沒有指定文件的位置。

getClass().getResource用於定位類路徑中的資源/文件;例如,資源可能會打包在你的jar中。在這種情況下,您無法將其打開爲File;見Raffaele的迴應。

如果您要查找的文件系統上的資源/文件,然後直接創建文件對象,而getResource()

新的文件( 「/世界/ world1.txt」)

0

我正在使用Netbeans,並且獲得了類似的結果。當我從C驅動器定義文件路徑並運行我的代碼時,它指出:訪問被拒絕。

以下代碼運行正常,只是將您的文件位置追溯到源(src)文件。

//EXAMPLE FILE PATH 
String filePath = "src\\solitaire\\key.data"; 

try { 
    BufferedReader lineReader = new BufferedReader(new FileReader(filePath)); 

    String lineText = null; 

    while ((lineText = lineReader.readLine()) != null) { 
     hand.add(lineText); 

     System.out.println(lineText); // Test print of the lines 
    } 

    lineReader.close(); // Closes the bufferReader 

    System.out.print(hand); // Test print of the Array list 
} catch(IOException ex) { 
    System.out.println(ex); 
}  
+0

雖然你可以使用'try'-with-resources塊,因爲你使用了'BufferedReader':try(BufferedReader lineReader = new BufferedReader(new FileReader(filePath))){ '。順便說一下,歡迎來到[so]!不要忘記參加[旅遊] :) – Unihedron 2014-11-09 06:25:44