Android导出数据库到内部存储

时间:2017-09-14 15:29:27

标签: android

在我的应用中我正在尝试制作可以将数据库从/data/data/com.example.damian.sshconnection/databases/ssh.db导出到内部存储/sdcard的选项。这是我的代码:

private void exportDatabase(){
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.example.damian.sshconnection" +"/databases/ssh.db";
    String backupDBPath = "/sdcard/ssh.db";
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

AndroidManifest.xml的权限

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

但是我收到了这个错误:

java.io.FileNotFoundException: /sdcard/ssh.db (Permission denied)

我还可以做些什么来从应用程序访问存储?

1 个答案:

答案 0 :(得分:1)

对于android 6+,除了manifest权限外,你还应该在运行时询问权限。看一下this文章;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

ActivityCompat.requestPermissions(getActivity(), new String[]{
    Manifest.permission.WRITE_EXTERNAL_STORAGE,
    Manifest.permission.READ_EXTERNAL_STORAGE
},666); // 666 is any number,to manually identify permission request in onRequestPermissionsResult callback