1

我有一个需要保存文件的 Android 应用程序。我创建这样的文件:

FileOutputStream fOut = openFileOutput(fileName, 
                    MODE_WORLD_READABLE);
            osw = new OutputStreamWriter(fOut);

我这样打开它:

FileInputStream srcFileStream = openFileInput(fileName);

这适用于内部存储器文件。我在我的应用程序中添加了一个偏好,用户可以在其中选择将文件保存到 sd 卡。我试试这个命令:

if (Prefs.getCard(this))
        fileName="/sdcard/"+fileName;

这意味着如果 Prefrences 是 yes,我会在文件名前添加“/sdcard/”。其余代码保持不变,

这似乎不起作用,因为我得到一个例外:

File /sd/file1 contains a path seperator

我如何使用相同的代码来保存到 SD 卡和内部存储器,只需像上面尝试的那样进行小修改?

4

3 回答 3

3

您当然没有忘记在清单中添加正确的权限...

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

您还可以尝试使用以下方式访问外部路径:

Environment.getExternalStorageDirectory();

我已经看到不同的外部路径名,具体取决于设备......

于 2012-05-07T14:03:42.920 回答
2

这应该工作..

String baseDir = "";
String fileName = "myFile.txt";
FileOutputStream fOut = null;
if (Prefs.getCard(this)) {
    baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(baseDir + fileName);
    fOut = new FileOutputStream(file)
}  else {
    fOut = openFileOutput(fileName, MODE_WORLD_READABLE);
}
if (fOut != null) {
    osw = new OutputStreamWriter(fOut);
    ...
}
于 2012-05-07T13:58:33.980 回答
0

编辑被七人组击败:

你可以尝试这样的事情:

File f = Environment.getExternalStorageDirectory(); 
String fullfilename = f.getAbsoluteFile() + "/Android/data/NameOfApp/fileshere/" ;

File folderToWrite = new File(fullfilename);
folderToWrite.mkdirs();

File fileToWrite = new File(fullfilename,"filename.txt");
于 2012-05-07T14:00:14.537 回答