在我的应用中我正在尝试制作可以将数据库从/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)
我还可以做些什么来从应用程序访问存储?
答案 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