import/export to android sqlite database

前端 未结 2 1899
死守一世寂寞
死守一世寂寞 2020-12-09 14:13

Ive seen a few posts on how to import and export a database in android and i found these code, but i cant seem to make it work. I get the error java.io.filenotfoundexception

相关标签:
2条回答
  • 2020-12-09 14:43

    Above accepted answer will not work for Android version on or above 6 because database path is different.

    please check below code . It will work on all devices.

        public static boolean exportDB(Context context) {
        String DATABASE_NAME = "my.db";
        String databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
        String inFileName = databasePath;
        try {
            File dbFile = new File(inFileName);
            FileInputStream fis = new FileInputStream(dbFile);
    
            String outFileName = Environment.getExternalStorageDirectory() + "/" + DATABASE_NAME;
    
            OutputStream output = new FileOutputStream(outFileName);
    
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            //Close the streams
            output.flush();
            output.close();
            fis.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-09 15:00

    SQlite database to our local file system-

    Function declaration-

            try {
                backupDatabase();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
    

    Function defined-

    public static void backupDatabase() throws IOException {
            //Open your local db as the input stream
            String inFileName = "/data/data/com.myapp.main/databases/MYDB";
            File dbFile = new File(inFileName);
            FileInputStream fis = new FileInputStream(dbFile);
    
            String outFileName = Environment.getExternalStorageDirectory()+"/MYDB";
            //Open the empty db as the output stream
            OutputStream output = new FileOutputStream(outFileName);
            //transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer))>0){
                output.write(buffer, 0, length);
            }
            //Close the streams
            output.flush();
            output.close();
            fis.close();
        }
    
    0 讨论(0)
提交回复
热议问题