在android中写入SD卡总是返回False

时间:2016-03-30 13:30:37

标签: android android-sdcard

大家好我必须将我的sqlite数据库复制到下载代码下面。但是,如果(sd.canWrite())总是返回false ...我坚持这个,是的,我已经添加到我的清单。我在真实设备上而不是虚拟设备。 Ty寻求帮助

private void copyDbToExternal(Context context) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()){
            String currentDBPath = "//data//data//" + context.getApplicationContext().getPackageName() + "//databases//"
                    + "qamatrisdb";
            String backupDBPath = "qamatrisdb";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:1)

您的代码与SD卡无关。您的代码正在写入external storage,而不是removable storage

如果canWrite()正在返回false,您可能会错过WRITE_EXTERNAL_STORAGE权限,或者您可能将targetSdkVersion设置为23或更高且未处理Android 6.0及更高版本运行时权限。

另外,请将现有的currentDBPath逻辑替换为a call to getDatabasePath()

答案 1 :(得分:1)

您是否尝试过使用Dev.Android上的教程?

http://developer.android.com/training/basics/data-storage/files.html

访问外部存储的示例:

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}