0

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();
    }
  • If you wanna know if a file exists under a certain path then use File.exists(). – blackapps Apr 16 '20 at 21:05
  • 1
    Do you get an exception thrown? If so, which one? Or is the `scores`-string just empty? – itzFlubby Apr 16 '20 at 21:07
  • 1
    `new File("Extra Files/history.txt")` You use a relative path. The File class expects a full path. Please tell your full path. – blackapps Apr 16 '20 at 21:09
  • use `System.out.println(new File(".").getCanonicalPath().toString());` to display the working directory of the java process. Your file is found relative to that. – k5_ Apr 16 '20 at 21:12
  • @itzFlubby I got a FileNotFoundException exception – Johnny Peacock Apr 16 '20 at 22:09
  • @blackapps I tried the full file path and it didn't work, ```file.exists()``` comes back as false so what can I do from there – Johnny Peacock Apr 16 '20 at 22:12
  • The file isn't where you said it was, relative to the current working directory when you executed the code . You don't need the absolute or canonical path here. [tag:BufferedReader] has nothing to do with it. – user207421 Apr 16 '20 at 23:54

1 Answers1

1

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();
}
  • When you say res/raw folder, is that res or raw folder or the raw folder in the res folder as I don't have a raw folder. – Johnny Peacock Apr 16 '20 at 22:50
  • I meant the raw folder in the res folder. If you don't have one you can just create it either in android studio or use and external file navigator and create the folder through that (I think I just used windows explorer to create mine). – Nicolas125841 Apr 16 '20 at 22:53
  • I tried the first method ```context.getAssets().open("filename")``` gut that didn't work, when I try the second method it says it has to be an integer, any idea what I have to put there? – Johnny Peacock Apr 16 '20 at 23:02
  • You need to put the R.raw.name ID in as the input integer with name being whatever the name of the file is without the extension. – Nicolas125841 Apr 16 '20 at 23:08
  • So that worked however, the when I read from it it gives me a NullPointerException, sorry to be a pain, any ideas? – Johnny Peacock Apr 16 '20 at 23:20
  • Just wondering, does the file have anything in it? Sorry if this is a dumb question. – Nicolas125841 Apr 16 '20 at 23:22
  • It didn't but I wrote some random stuff in it and I got the same exception thrown – Johnny Peacock Apr 16 '20 at 23:24
  • Could you try something real quick and tell me what the value of context.getResources().openRawResource(R.raw.resourceName).availible() is? with resourceName, of course, being whatever the name of the file is – Nicolas125841 Apr 16 '20 at 23:26
  • Oh sorry but I just realised its another error and it does work, and available() is 1. Sorry – Johnny Peacock Apr 16 '20 at 23:41
  • Just a quick question, other than writing some random stuff in the file to make it not null, is there a better way to do so? – Johnny Peacock Apr 16 '20 at 23:50
  • Also, I have just tried to write something using the other method, luckily it doesn't give me an error however it doesn't write anything to the file, any ideas there? Sorry to be a pain. – Johnny Peacock Apr 17 '20 at 00:19
  • Well for the first question, you could check using the .availible method on the inputstream or the .length method on the file to see if there are any bytes availible to read, if not (if it returns a 0) then you can just skip reading from the file until writing because nothing is there to be read (This isn't a surefire way but it is better than nothing). As for the second question, (if I understand correctly you are using the .getFilesDir() file right?) the changes wont appear in android studio because they are only made on the phone which ran the program and can only be viewed by the app – Nicolas125841 Apr 17 '20 at 02:54
  • Ok that makes sense, should I be able to see it change using ```System.out.println(fileContents)``` – Johnny Peacock Apr 17 '20 at 17:22
  • I'm not 100% sure if System.out works on all of the physical devices, but it is worth a try. If not then Android's Log class e.g. Log.d(fileContents) should do the same thing. – Nicolas125841 Apr 17 '20 at 19:02
  • Well I tried both methods and obviously looked at the output on my actual device however when I try to write something it only writes the current thing and not the previous stuff also. I am first reading the file using a bufferedreader and then writing that + new data to the file, any ideas? – Johnny Peacock Apr 17 '20 at 19:59
  • I added the code to my question, I still can't get it to work though. – Johnny Peacock Apr 17 '20 at 20:54
  • I'm very sorry, I forgot how the .append() worked on the BufferedWriter, it won't do what I said it would. Instead when you make the BufferedWriter instance do it like this: new BufferedWriter(new FileWriter(file, true)) the true will make the .write method append to the file – Nicolas125841 Apr 17 '20 at 21:12
  • I added the code and added lots of Log statements but it still won't write to the file. – Johnny Peacock Apr 18 '20 at 23:09