Johnny Peacock
Johnny Peacock

Reputation: 15

Why is my file not found when using a FileReader in java

I am trying to find a file I have saved in android studio. I have tried everything: putting the full directory, putting the the file in a new folder in that directory, using file.getAbsolutePath(), declaring a file before or putting the file directly into the reader(BufferedReader r = new BufferedReader(new FileReader("history.txt")); Here is the code:

        File file = new File("Extra Files/history.txt");
        BufferedReader r = new BufferedReader(new FileReader(file.getAbsolutePath()));
        String scores = r.readLine();
        r.close();

No matter what I try it does not seem to work any other ideas, can you not use text files like this in android studio or ???

    public void write_score(int ns) throws IOException {
        File file = new File(context.getFilesDir(), "history.txt");
        BufferedWriter w = new BufferedWriter(new FileWriter(file));
        w.append(String.valueOf(ns)).append(",");
        w.close();
    }

Upvotes: 0

Views: 1393

Answers (1)

Nicolas125841
Nicolas125841

Reputation: 148

If you just need to read from the file, you could put it in the assets or res/raw folder and read from them using context.getAssets().open("filename") or context.getResources().openRawResource(R.raw.resourceName) to get the input streams and then using BufferedReader(new InputStreamReader(fileStream)) to get the reader . If not, this post, should have the answer to let you to read from a different folder.

If you want to write to it, though, one way is to use the app-specific internal files which can be accessed with

File file = new File(context.getFilesDir(), filename);

But you will first need to create the history.txt file using file.createNewFile() and fill it with whatever you wanted because it won't already exist the first time you try to access it. After that it should be fine though. I hope this helps.

Edit:

Here is some sample code to read/write to the internal file

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);//Or use Log.d(line);
        }
} catch (IOException e) {
    e.printStackTrace();
}

and

 public void write_score(int ns) throws IOException {
    File file = new File(context.getFilesDir(), "history.txt");
    BufferedWriter w = new BufferedWriter(new FileWriter(file, true));//true makes it append
    w.write(String.valueOf(ns) + ",");
    w.close();
}

Upvotes: 1

Related Questions