0

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.

In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.

This code is what I use to create the file and read info from it, used in the onCreate() method of activity

    try {

        String brain = "brain";
        File file = new File(this.getFilesDir(), brain);
        if (!file.exists()) {
            file.createNewFile();
        }      

        BufferedReader in = new BufferedReader(new FileReader(file));
        String s; // This feeds the object MegaAndroid with the strings, sequentially 
        while ((s = in.readLine()) != null) {
            MegaAndroid.add(s);
        }
        in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

After that, every time the user inputs some text, the strings are saved onto the file:

    try {

        String brain = "brain";
        File file = new File(this.getFilesDir(), brain);
        if (!file.exists()) {
            file.createNewFile();
        }

    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    out.write(message); // message is a string that holds the user input
    out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

For some reason, however, every time the application is killed, the data is lost. What am I doing wrong?

EDIT: Also, if I were to access this file from another class, how can I?

16
  • Try calling out.flush() before closing it. Commented Feb 6, 2013 at 16:20
  • Post your logcat please Commented Feb 6, 2013 at 16:21
  • is the content being saved inside the file ?? Commented Feb 6, 2013 at 16:21
  • @RaghavSood i think BufWriter.close() would call flush() implicitly. Commented Feb 6, 2013 at 16:22
  • @PremGenError: why wouldn't it be? the bufferedWriter "out" use the file "file" as the parameter... Isn't that how it's supposed to be? Commented Feb 6, 2013 at 16:22

2 Answers 2

1

As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:

BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();

However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to

This is line #1This is line #2

Instead of the desired

This is line #1
This is line #2

which would be corrected by having the BufferedWriter pass a newline after each write to the file.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, worked perfectly. Thank you very much, you're a lifesaver!
1

This is what I do for file reading.

try{

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
        dir.mkdirs();

        Log.d(TAG,"path: "+dir.getAbsolutePath());
        File file = new File(dir, "VERSION_FILENAME");

        FileInputStream f = new FileInputStream(file);

        //FileInputStream fis = context.openFileInput(VERSION_FILENAME);
        BufferedReader reader = new BufferedReader(new InputStreamReader(f));

        String line = reader.readLine();
        Log.d(TAG,"first line versions: "+line);
        while(line != null){
            Log.d(TAG,"line: "+line);
            //Process line how you need 
            line = reader.readLine();
        }

        reader.close();
        f.close();
    }
    catch(Exception e){
        Log.e(TAG,"Error retrieving cached data.");

    }

And the following for writing

try{

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
        dir.mkdirs();
        File file = new File(dir, "CONTENT_FILENAME");

        FileOutputStream f = new FileOutputStream(file);

        //FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));

        Set<String> keys = Content.keySet();

        for(String key : keys){

            String data = Content.get(key);
            Log.d(TAG,"Writing: "+key+","+data);

            writer.write(data);
            writer.newLine();
        }

        writer.close();
        f.close();

    }
    catch(Exception e){
        e.printStackTrace();
        Log.e(TAG,"Error writing cached data.");

    }

You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.