birdcage
birdcage

Reputation: 2676

java.io.FileNotFoundException for text file

I have a txt file in the root folder of my Android project called KARIN.txt. I am trying to reach it by FileReader but I am having the following error:

java.io.FileNotFoundException: /KARIN.txt: open failed: ENOENT (No such file or directory)

How I am trying to reach that file is as following:

BufferedReader br = new BufferedReader(new FileReader("KARIN.txt"));

I am confused that why it is not allowing me to read the file.

Upvotes: 0

Views: 1476

Answers (1)

TheJavaCoder16
TheJavaCoder16

Reputation: 591

If KARIN.txt is built into your project you should put it in the assets folder and access it via the AssetManager.

public String loadFile(String file){
        AssetManager am = getActivity().getAssets();
        InputStreamReader ims = null;
        BufferedReader reader = null;
        String data = "File not available!";
        try {
            ims = new InputStreamReader(am.open(file), "UTF-8");
            reader = new BufferedReader(ims);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(ims != null){
            try {
                String mLine = reader.readLine();
                data = "";
                while(mLine != null){
                    data+= mLine;
                    mLine = reader.readLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                if (reader != null) {
                     try {
                         reader.close();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                }
            }
        }
        return data;
}

Upvotes: 3

Related Questions