简体   繁体   中英

Android file keeps recreating on external storage

I managed to save a file to external storage and write some informations inside, the only problem is when I open the app again it will recreate the file and all saved data is lost.

Does cacheFile = new java.io.File(getExternalFilesDir("")+"/cache.txt"); recreate the cache.txt if still exists or the problem is somewhere else ?

Full code on execution:

cacheFile = new java.io.File(getExternalFilesDir("")+"/cache.txt");
        if(cacheFile.exists() && !cacheFile.isDirectory()) {
            Log.i("TEST","Entering in cache");
            try {
                writer = new FileWriter(cacheFile);
                BufferedReader br = new BufferedReader(new FileReader(cacheFile));
                String tempo;
                while((tempo = br.readLine()) != null){
                    Log.i("TEST","Reading from cache "+tempo);
                    if (tempo.contains("http")) {
                        musicUrl.add(tempo);
                    }
                    else {
                        myDataList.add(tempo);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {
            try {
                Log.i("TEST", "Creating cache ? " + cacheFile.createNewFile() + " in " + getExternalFilesDir(""));
                writer = new FileWriter(cacheFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

After adding some lines to the file I write

writer.flush();
writer.close();

The file will remain as I want untill I open the app again.

Use this -

writer = new FileWriter(cacheFile, true);

This means that you will append data to the file. see also here - FileWRiter

If you want to read and then write to the same file, then,

The non confusing solution is, first open the file in read mode, read the content and "Close" it properly, then open file in a write mode, write data and "close" the file properly.

That means do one thing at a time, either read from the file or write in the file.(Always close the file after completion of reading or writing, so file will not get locked.)

Use "InputStream" for reading from a file and "OutputStream" for writing in the file.

Sample code for reading a file :

try {
    FileInputStream in = new FileInputStream("pathToYourFile");
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String lineString;

    while ((lineString = br.readLine()) != null) {
        // the line is stored in lineString
    }
} catch(Exception e) {
    e.printStackTrace();
}

Sample code for writing a file :

    // Gets external storage directory
    File root = android.os.Environment.getExternalStorageDirectory();

    // File's directory
    File dir = new File(root.getAbsolutePath() + File.separator + "yourFilesDirectory");

    // The file
    File file = new File(dir, "nameOfTheFile");
//if file is not exist, create the one
if(!file.exists()){
                    file.createNewFile();
}

    // Writes a line to file
    try {
        FileOutputStream outputStream = new FileOutputStream(file, true);
        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
        writer.write("A line\n");
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM