将同一文件保存到具有多个名称的SD卡

时间:2013-07-03 05:57:25

标签: android android-edittext android-button

这是将文件写入SD卡的代码。

    try {
        File file = Environment.getExternalStorageDirectory();
        File myFile = new File(file, "sample.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(Globals.obj.toString());
        myOutWriter.close();
        fOut.close();
        Toast.makeText(getApplicationContext(), "Written successfully",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }

这里'sample.txt'是保存到SD卡的文件。用户输入EditText值后,点击Button即可将其保存到卡片中。另一个用户来了,他的内容保存为'sample1.txt',另一个用户保存为'sample2.txt','sample3.txt'(增量顺序)等等。有谁能告诉我怎么做??

1 个答案:

答案 0 :(得分:1)

尝试这种方法:

File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()){
 ...
}

OR

File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, "yourpath");
for (File f : yourDir.listFiles()) {
    if (f.isFile())
        String name = f.getName();
        // substr the name to find the last digits
}

您可以检查文件是否存在,然后附加相应的数字。

相关问题