Can't copy SQLite database from assets

后端 未结 4 1768
情书的邮戳
情书的邮戳 2020-12-04 00:05

I try to copy SQLite database from assets directory to access it later. But I fail to do it!

public class DatabaseAdapter {
    private static String DB_PATH         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 00:53

    public static void copyDatabase(final Context ctx, String dbName) {
        if (ctx != null) {
            File f = ctx.getDatabasePath(dbName);
            if (!f.exists()) {
    
                // check databases exists
                if (!f.getParentFile().exists())
                    f.getParentFile().mkdir();
    
                try {
                    InputStream in = ctx.getAssets().open(dbName);
                    OutputStream out = new FileOutputStream(f.getAbsolutePath());
    
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = in.read(buffer)) > 0) {
                        out.write(buffer, 0, length);
                    }
                    in.close();
                    out.close();
                    Logger.i("Database copy successed! " + f.getPath());
                } catch (Exception ex) {
                    Logger.e(ex);
                }
            }
        }
    }
    

提交回复
热议问题