Search code examples
javaandroidbufferedreaderfileoutputstream

FileOutputStream only writes the message into the file if I read it between saves


I'm trying to write a File read/write class and I made an example activity for this with a button to save to a file I create, a button to read from the file, and a textView to read things from. I tried a few test cases to see if my FileRW worked and it works fine if I read the file after every message but If I try to save multiple messages onto the file without reading between successive tries, only the latest message gets written to the file. I don't know what is causing this behavior.

All the help is appreciated.

file = new File(getFilesDir() + "CheckFile.txt");

save.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        try
        {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(text.getText().toString().getBytes());
            fos.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
});


read.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(file));

            while ((line = br.readLine()) != null)
            {
                textString.append(line);
                textString.append('\n');
            }
            br.close();
            Log.i("Ranai text", textString+"");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
});

Solution

  • By default, FileOutputStream will overwrite the contents of the output file when you write to it. By passing the second argument of the constructor as true, you can tell the FileOutputStream to append to the existing contents of the file instead of overwriting.

    FileOutputStream fos = new FileOutputStream(file, true);