为什么我不能将文件保存在外部存储设备或存储卡中?

时间:2018-02-09 08:06:46

标签: android file android-external-storage

我想在我的存储卡中创建一个备份文件,但它只是返回一个未找到文件的例外。我正在指定应保存数据的路径。当我选择内部存储时,文件已保存但当我将其更改为外部存储时,它会返回我找不到的文件。

以下是截图: enter image description here

final Preference prefStoragePath = findPreference("key_storage_path");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String pref_storage_path = settings.getString("set_storage_path",null);
startingDir = (pref_storage_path!=null)? pref_storage_path : Environment.getExternalStorageDirectory().toString();

Preference prefBackupManual = findPreference("key_backup_manual");
final String root = Environment.getExternalStorageDirectory().toString();
prefBackupManual.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        createBackupData(startingDir);
        return false;
    }
});

private void createBackupData(String dir){
    String filename = "BackupData.txt";
    String data = resultSet().toString();
    try{
        byte[] sha1hash;
        File myFile =  new File(dir,filename);
        sha1hash = data.getBytes("UTF-8");
        String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
        FileOutputStream fos = new FileOutputStream(myFile);
        fos.write(base64.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
    }finally {
        Toast.makeText(getActivity(),"File saved in " + dir + "/" + filename ,Toast.LENGTH_SHORT).show();
    }
}

1 个答案:

答案 0 :(得分:1)

发生了什么?

您正在尝试将数据写入不存在的文件,因此会引发FileNotFoundExceptionFile(String, String)构造函数不会创建实际文件,您必须自己处理。

如何解决?

检查您的应用是否在Manifest中声明了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />。如果您要定位SDK 23或更高版本,则应check and request that permission at runtime

您的保存方法应如下所示:

private void createBackupData(String dir) {
    String filename = "BackupData.txt";
    String data = resultSet().toString();
    FileOutputStream fos = null;
    try {
        byte[] sha1hash;
        File myFile = new File(dir, filename);
       //NOTE: your file will be overwritten in case it already exists
        if (myFile.exists() || myFile.createNewFile()) {
            sha1hash = data.getBytes("UTF-8");
            String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
            fos = new FileOutputStream(myFile);
            fos.write(base64.getBytes());
            Toast.makeText(getActivity(), "File saved in " + dir + File.separator + filename, Toast.LENGTH_SHORT).show();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

注意:更好的方法是使用Environment.getExternalStorageDirectory().getAbsolutePath()代替Environment.getExternalStorageDirectory().toString()