Java - FilenotfoundException for reading text file

和自甴很熟 提交于 2019-12-02 13:18:21

The best way to do this is to put it in your classpath then getResource()

package com.sandbox;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class Sandbox {

    public static void main(String[] args) throws URISyntaxException, IOException {
        new Sandbox().run();
    }

    private void run() throws URISyntaxException, IOException {
        URL resource = Sandbox.class.getResource("/my.txt");
        File file = new File(resource.toURI());
        String s = FileUtils.readFileToString(file);
        System.out.println(s);
    }


}

I'm doing this because I'm assuming you need a File. But if you have an api which takes an InputStream instead, it's probably better to use getResourceAsStream instead.

Notice the path, /my.txt. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource and getResourceAsStream to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).

BTW, if you get a null pointer exception on the line that does new File, that means that you haven't specified the correct classpath for the file.

As far as I remember the default directory with be the same as your project folder level. Put the file one level higher.

-Project/
 ----src/
 ----test/
-Highscores.scr

If you are building your code on your eclipse then you need to put your Highscores.scr to your project folder. Try that and check.

You can try to run the following sample program to check which is the current directory your program is picking up.

File f = new File(".");
System.out.println("Current Directory is: " + f.getAbsolutePath());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!