[英]Copy Database with Android 4.4
I have a Problem when I want to copy a database from the assets to the device. 我想将数据库从资产复制到设备时遇到问题。 I always get a FileNotFoundException.
我总是收到FileNotFoundException。 Also terminate and relaunch don't work.
同时终止并重新启动也不起作用。 In the Debugger the content of the variables seems to be ok.
在调试器中,变量的内容似乎还可以。
My code: 我的代码:
private void copyDatabase() throws IOException {
if (DEBUG) Log.d(TAG, "copyDatabase");
String DB_PATH = myContext.getDatabasePath(DATABASE_NAME).toString();
AssetManager assetManager = myContext.getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(DATABASE_NAME);
} catch (IOException ex) {
Log.d(TAG, "InputStream Exception");
}
if (inputStream != null) {
OutputStream outputStream = new FileOutputStream(DB_PATH);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
The Line OutputStream outputStream = new FileOutputStream(DB_PATH); 行OutputStream outputStream = new FileOutputStream(DB_PATH); raises the exception.
引发异常。
DB_PATH: /data/data/com.wiget.autokatalog/databases/autokatalog.db3 cause ErrnoException (id=830031910480) detailMessage "/data/data/com.wiget.autokatalog/databases/autokatalog.db3: open failed: ENOENT (No such file or directory)" (id=830031912168)
DB_PATH:/data/data/com.wiget.autokatalog/databases/autokatalog.db3原因ErrnoException(id = 830031910480)detailMessage“ /data/data/com.wiget.autokatalog/databases/autokatalog.db3:打开失败:ENOENT(否这样的文件或目录)”(id = 830031912168)
I thought that the File will be created with this line. 我认为将使用此行创建文件。
Could there be a permission Problem (eg something missing in the AndroidManifest) ? 可能存在权限问题(例如,AndroidManifest中缺少的东西)吗?
Thanks for you help. 感谢您的帮助。
/Andre /安德烈
/data/data/com.wiget.autokatalog/databases/ maybe not exists if you have not created any database before this. 如果您之前尚未创建任何数据库,则/data/data/com.wiget.autokatalog/databases/可能不存在。 Try the following:
请尝试以下操作:
public File copyFromAssetsTo(String fromFile, String toPath) {
AssetManager assetManager = context.getAssets();
try {
String[] arr = toPath.split("/");
String fileName = arr[arr.length - 1];
String fileDirPath = toPath.replaceAll(fileName, "");
File fileDir = new File(fileDirPath);
if(!fileDir.exists()) {
fileDir.mkdirs();
}
File file = new File(fileDir, fileName);
InputStream in = assetManager.open(fromFile);
OutputStream out = new FileOutputStream(file);
copyFile(in, out);
out.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.