簡體   English   中英

Android文件不斷在外部存儲上重新創建

[英]Android file keeps recreating on external storage

我設法將文件保存到external storage並在其中寫入一些信息,唯一的問題是當我再次打開該app時,它將重新創建該file並且所有保存的數據都將丟失。

是否cacheFile = new java.io.File(getExternalFilesDir("")+"/cache.txt"); 重新創建cache.txt(如果仍然存在)或問題是否在其他地方?

完整的執行代碼:

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

在文件中添加一些行后,我寫

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

該文件將保持我想要的狀態,直到再次打開該應用程序為止。

用這個 -

writer = new FileWriter(cacheFile, true);

這意味着您將把數據追加到文件中。 另請參見此處-FileWRiter

如果您要讀取然后再寫入同一文件,

不會混淆的解決方案是,首先以讀取模式打開文件,讀取內容並正確“關閉”,然后以寫入模式打開文件,寫入數據並正確“關閉”文件。

這意味着一次執行一項操作,無論是從文件中讀取文件還是在文件中寫入文件(總是在完成讀取或寫入操作后關閉文件,因此文件不會被鎖定)。

使用“ InputStream”讀取文件,使用“ OutputStream”寫入文件。

讀取文件的示例代碼:

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

編寫文件的示例代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM