2017-02-18 68 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

更新**问题**以显示当前代码,并在此时注意:源代码中的单个空白行是需要的*。 '{'之后或'}'之前的空行通常也是多余的。 –