Alberto Rossi
Alberto Rossi

Reputation: 1800

Android save text file

The question is pretty common and I have googled it a few but I still have problems. I have to save in a text file some data for a game that I am trying to develop. This is the code:

if (!isSecond(game[k])) {

            //Where I'd like to save the file
            File myFile = new File(Environment.getExternalStorageDirectory() + "/flagQuiz/record.txt");

             //Try to save my file
             try {

                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter = 
                                        new OutputStreamWriter(fOut);

                //correctGuess and TimeElapsed are two integers
                myOutWriter.append(String.valueOf(correctGuess) + "-" + String.valueOf(TimeElapsed));
                myOutWriter.close();
                fOut.close();

             } catch (IOException e) {

                 e.printStackTrace();

             }

}

The log cat shows me this kind of error:

enter image description here

I have declared the possibility to save stuff in the SD Card in this way I guess:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Where is the mistake? flagQuiz folder is already created at runtime.

Upvotes: 1

Views: 162

Answers (1)

Yogesh Seralia
Yogesh Seralia

Reputation: 350

Be sure to check if file.exists() if true then delete it and create new one else false then just carry on with your try block

Upvotes: 2

Related Questions