Android文件不断在外部存储上重新创建

时间:2015-07-24 08:52:14

标签: java android

我设法将文件保存到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();

文件将保持原样,直到我再次打开应用程序。

2 个答案:

答案 0 :(得分:1)

使用此 -

writer = new FileWriter(cacheFile, true);

这意味着您将数据附加到文件中。 另见 - FileWRiter

答案 1 :(得分:0)

如果要读取然后写入同一文件,则

非混淆的解决方案是,首先以读取模式打开文件,读取内容并正确“关闭”,然后以写入模式打开文件,写入数据并正确“关闭”文件。

这意味着一次做一件事,无论是从文件中读取还是在文件中写入。(在读取或写入完成后始终关闭文件,因此文件不会被锁定。)

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