我一直在尝试创建应用程序数据库的副本并将其保存到手机的根目录,但没有运气。我的日志去了:
第一步
STEP DEAD
显然if (sd.canWrite())
是第一个错误?有人能帮忙吗?我的想法已经不多了。谢谢
public void save() {
File data = Environment.getDataDirectory();
File sd = new File(Environment.getExternalStorageDirectory().toString());
sd.mkdirs();
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP ONE");
if (sd.canWrite()) {
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP TWO");
String currentDBPath = "/data/com.test.example/databases/example_db";
String backupDBPath = "/mytest" + "version_two" + ".db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP THREE");
if (currentDB.exists()) {
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP FOUR");
FileChannel src;
try {
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP FIVE");
src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB)
.getChannel();
try {
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP SIX");
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP ONE DEAD");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP TWO DEAD");
e.printStackTrace();
}
}
}else{
Log.d("XXXXXXXXXXXXXXXXXXX", "STEP DEAD");
}
}
我的清单剪辑 - 我不知道android:allowBackup="true"
是如何到达那里的
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
在模拟器输出上:
01-13 14:16:13.082: D/XXXXXXXXXXXXXXXXXXX(30105): STEP ONE
01-13 14:16:13.082: D/XXXXXXXXXXXXXXXXXXX(30105): STEP DEAD
在设备输出上:
01-13 14:16:13.082: D/XXXXXXXXXXXXXXXXXXX(30105): STEP ONE
01-13 14:16:13.082: D/XXXXXXXXXXXXXXXXXXX(30105): STEP TWO
01-13 14:16:13.082: D/XXXXXXXXXXXXXXXXXXX(30105): STEP THREE
01-13 14:16:13.082: D/XXXXXXXXXXXXXXXXXXX(30105): STEP FOUR
01-13 14:16:13.082: D/XXXXXXXXXXXXXXXXXXX(30105): STEP FIVE
01-13 14:16:13.090: D/XXXXXXXXXXXXXXXXXXX(30105): STEP SIX
答案 0 :(得分:1)
File sd = new File(Environment.getExternalStorageDirectory().toString());
好吧,因为Environment.getExternalStorageDirectory()返回一个你不创建新实例的文件。你可以用这种方式改变它:
File sd = Environment.getExternalStorageDirectory();
sd.mkdirs();
肯定会失败,因为您在/
和/mnt
内没有写权限,sd
指向的目录也应该已经退出WRITE_EXTERNAL_STORAGE
:您是否将其添加到AndroidManifex文件中?可能因为忘记添加权限