![](/img/trans.png)
[英]Android copy SQLite database from asset not work on KitKat 4.4
[英]Copy Database with Android 4.4
我想將數據庫從資產復制到設備時遇到問題。 我總是收到FileNotFoundException。 同時終止並重新啟動也不起作用。 在調試器中,變量的內容似乎還可以。
我的代碼:
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();
}
}
行OutputStream outputStream = new FileOutputStream(DB_PATH); 引發異常。
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)
我認為將使用此行創建文件。
可能存在權限問題(例如,AndroidManifest中缺少的東西)嗎?
感謝您的幫助。
/安德烈
如果您之前尚未創建任何數據庫,則/data/data/com.wiget.autokatalog/databases/可能不存在。 請嘗試以下操作:
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.