Korbin Gugisberg
Korbin Gugisberg

Reputation: 35

How to stop a file from overwriting itself when using FileOutputStream using openFileOutput in Android

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();
                    }
                }
            });
    
        }
    }

Upvotes: 1

Views: 180

Answers (2)

Jamez
Jamez

Reputation: 41

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
        }

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89224

Use the append mode when constructing the FileOutputStream.

FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE | MODE_APPEND);

Upvotes: 2

Related Questions