【问题标题】:Copy Database with Android 4.4使用 Android 4.4 复制数据库
【发布时间】:2014-07-24 09:20:20
【问题描述】:

我想将数据库从资产复制到设备时遇到问题。我总是得到一个 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 中缺少某些内容)?

感谢您的帮助。

/安德烈

【问题讨论】:

    标签: android database android-4.4-kitkat


    【解决方案1】:

    /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;
    }
    

    【讨论】:

    • 感谢您,创建目录有助于解决问题。
    • 对不起,我没有足够的声望来投票:-(
    猜你喜欢
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2013-05-09
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    相关资源
    最近更新 更多