Miquel Perez
Miquel Perez

Reputation: 455

Calling OpenFileOutput inside a Button click listener in Android

I have a simple app with a button. I have a FileOutputStream defined globally in the MainActivity. Then on the onCreate() I initialize it. When the button is clicked, I open a new file output like:

outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes()); outputStream.close();

Sorry if the question sounds dumb, but does this code inside the button click listener create a new different file each time I click on the button? Like if I click 10 times to that button will I have 10 files in the actual app file directory? This concern comes because I realised the app keeps increasing its size when I check it on the internal storage settings. Is there any way to ensure that the file is only going to be created just on the first button click? Like creating it only if it hasn't been created yet.

Thanks.

Upvotes: 0

Views: 81

Answers (2)

GiapLee
GiapLee

Reputation: 436

  • You need only one file name not have any other name or
  • You can use check File exiting before create it again, try this code:

    File f = new File(filename); //file path

    if (!f.exists()){ 
    
      //do your code to create new file
    
    }
    

Upvotes: 0

Hungry Coder
Hungry Coder

Reputation: 1820

If your filename remains same, it will create the file for the first time and then open it again and again on subsequent button clicks. Take a look here in the official documentation:

Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.

Upvotes: 0

Related Questions