我正在尝试将zip格式的大型数据库文件(database.db)从服务器下载到某个文件夹(外部/内部存储),将其加载到应用程序的专用数据库存储中,并删除源文件(database.db.zip)。我已经下载并保存了源文件。
将数据库加载到专用存储时出现问题。类似于“android sqlite asset helper”,但这个库只有一个特定的源文件夹,从中获取数据库文件->“assets/databases/”,但我需要用其他目录替换资源。在我看来,这个图书馆的其余部分工作得很好。有什么办法做我想做的吗?
1)使用android downloadmanager下载database.db文件
2)将database.db文件移动到/data/data/package\u name/databases/
3)加载数据库

最佳答案

public static void copyDatabase(Context c, String DATABASE_NAME) {
        String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
        File f = new File(databasePath);
        OutputStream myOutput = null;
        InputStream myInput = null;
        Log.d("testing", " testing db path " + databasePath);
        Log.d("testing", " testing db exist " + f.exists());

        if (f.exists()) {
            try {

                File directory = new File("/mnt/sdcard/DB_DEBUG");
                if (!directory.exists())
                    directory.mkdir();

                myOutput = new FileOutputStream(directory.getAbsolutePath()
                        + "/" + DATABASE_NAME);
                myInput = new FileInputStream(databasePath);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }

                myOutput.flush();
            } catch (Exception e) {
            } finally {
                try {
                    if (myOutput != null) {
                        myOutput.close();
                        myOutput = null;
                    }
                    if (myInput != null) {
                        myInput.close();
                        myInput = null;
                    }
                } catch (Exception e) {
                }
            }
        }
    }

07-24 09:46
查看更多