1

I'm currently making an app that needs to save the number and write it into a text file. But every time it writes to the file. It overwrites the last things saved. Here is the code of the entire program in java.

package com.galaxy.nestetrisscores;
    
    
    import androidx.appcompat.app.AppCompatActivity;
    import android.os.Bundle;
    
    import java.io.FileOutputStream;
    import java.io.File;
    
    import android.view.View;
    import android.widget.*;
    
    
    public class MainActivity extends AppCompatActivity {
    
        private Button button;
        private EditText editNumber;
        private String file = "Scores.txt";
        private String fileContents;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            button = findViewById(R.id.button);
            editNumber = findViewById(R.id.editNumber);
    
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    fileContents = editNumber.getText().toString();
    
                    try {
                        FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE);
                        fOut.write(fileContents.getBytes());
                        fOut.close();
                        File fileDir = new File(getFilesDir(), file);
                        Toast.makeText(getBaseContext(), "File Saved at" + fileDir, Toast.LENGTH_LONG).show();
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    
        }
    }
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    Does this answer your question? [How to append text to an existing file in Java?](https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Gaël J Jun 20 '21 at 15:30
  • 2
    Can you show us what `openFileOutput()` has inside of it? It seems to me that the error lies in the constructor for the FOS. – dimitar.bogdanov Jun 20 '21 at 15:31

2 Answers2

2

Use the append mode when constructing the FileOutputStream.

FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE | MODE_APPEND);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

Not sure if this will be of any use, but a simple IF using the .exists() boolean method

File file = new File("file.txt");
        if (file.exists()) {
          System.err.println("File already exists");
          // Append to file
        } else {
           // Create File
        }
Jamez
  • 41
  • 1
  • 4