当我想将数据库从资产复制到设备时,我遇到了问题。我总是得到一个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();
}
}
Line 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:open 失败:ENOENT(没有这样的文件或目录)“(id = 830031912168)
我以为将使用此行创建文件。
是否存在权限问题(例如AndroidManifest中缺少某些内容)?
谢谢你的帮助。
/安德烈
答案 0 :(得分:0)
/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;
}