FileNotFoundException甚至当文件放在与类文件相同的文件夹中时

时间:2013-05-03 18:51:27

标签: java

我读了一个文件big.txt来填充我的HashMap。我已将文件放在class文件夹中的bin文件旁边。

但是,每当我想使用它时,都会显示错误java.io.FileNotFoundException ( No such file or directory )

这是怎么回事?

public ClassName() throws IOException{
        URL url = ClassName.class.getResource("big.txt");
        File file = new File(url.getPath());
        BufferedReader inp= new BufferedReader(new FileReader(file));
        // some code
        }
        inp.close();        
    }

为什么会这样? Plaese帮帮我吧!

3 个答案:

答案 0 :(得分:3)

您可以使用

访问类路径上的任何资源
public ClassName() throws IOException{
        // the path to your file is relative to the package of ClassName
        InputStream input = ClassName.class.getResourceAsStream("big.txt"); 

        BufferedReader inp = new BufferedReader(new InputStreamReader(input));

        // some code

        inp.close();        
}

URL url = ClassName.class.getResource("big.txt");
// check for null first
InputStream input = url.openStream();
BufferedReader inp = new BufferedReader(new InputStreamReader(input));

答案 1 :(得分:1)

如果您正在使用eclipse,我相信它实际上是在项目文件夹中查找,但不在文件的bin文件夹中,具体取决于设置。您应该尝试在那里移动big.txt,但如果您想更改代码,其他答案也是有用的。

答案 2 :(得分:0)

public ClassName() throws IOException{
        Scanner in = new Scanner(getClass().getResourceAsStream("big.txt"));
        //your stuff       
}
相关问题