2017-02-18 66 views
0

enter image description here的Java:如何使用掃描儀類讀取文本文件中的資源文件夾

import java.util.*; 
import java.io.File; 
import java.io.IOException; 

public class Test { 

    public static void main(String[] args) { 
     File source; 
     Scanner input; 
     String name; 
     String id; 
     Pokemon x; 
     ArrayList<Pokemon> pokelist = null; 

     try { 
      source = new File("/resources/gen1pokemon.txt"); 
      input = new Scanner(source); 
      input.useDelimiter(","); 
      while(input.hasNext()) { 
       id = input.next(); 
       name = input.next(); 
       x = new Pokemon(id,name); 
       pokelist.add(x); 

       input.nextLine(); 
      } 
     } catch(Exception e) { 
      System.out.println(e); 
     } 
     System.out.println(pokelist.get(0).getName()); 
    } 
} 

我有我的資源文件夾中的文本文件,我想讀,使用掃描儀類,但我得到一個錯誤。 java.io.FileNotFoundException:\ resources \ gen1pokemon.txt(系統找不到指定的路徑)線程「main」中的異常

任何想法可能導致這種情況?我環顧四周,試圖把「class.getResource(」文件名「)」引用,但我也有一個錯誤,當聲明文件時也這樣做。

回答

0

你試過/src/resources/gen1Pokemon.txt

路徑可能有點棘手,根據項目的結構嘗試不同的版本。

1

應用程序資源在部署時將成爲嵌入式資源,所以現在就開始訪問它們是明智的做法。一個必須由URL而不是文件訪問。有關如何形成URL,請參閱info. page for embedded resource

要在掃描儀中使用URL,get an input stream from it,然後使用new Scanner(InputStream)

+0

input = new Scanner(Test.class.getResourceAsStream(「/ resources/gen1pokemon.txt」)); 這樣做修復它,謝謝,但現在我得到一個空指針異常,通過查看代碼,你可以找出可能導致什麼? –

+0

更新**問題**以顯示當前代碼,並在此時注意:源代碼中的單個空白行是需要的*。 '{'之後或'}'之前的空行通常也是多餘的。 –