备份sqlite数据库。 transferTo和transferFrom不工作

时间:2017-11-02 17:14:30

标签: android sqlite android-sqlite

我尝试通过将其复制到外部来备份我的应用数据库。我尝试下面的代码,但没有用。

backupButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                File sd = Environment.getExternalStorageDirectory();
                String state =  Environment.getExternalStorageState();
                String mounted = Environment.MEDIA_MOUNTED;
                if (mounted.equals(state)) {
                    File currentDB = context.getDatabasePath(DatabaseHelper.DATABASE_NAME);
                    File backupDB = new File(sd, "backupTester.db");

                    if (currentDB.exists()) {
                        FileChannel src = new FileInputStream(currentDB).getChannel();
                        FileChannel dst = new FileOutputStream(backupDB).getChannel();
                        src.transferTo(0,src.size(),dst);
                        src.close();
                        dst.close();
                        Toast.makeText(context, "DB EXPORTED", Toast.LENGTH_SHORT).show();
                    }
                }
                else Toast.makeText(context, "No SD Card", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(context, "backup not running", Toast.LENGTH_SHORT).show();
            }
        }
    });

2 个答案:

答案 0 :(得分:0)

这是我创建数据库副本的工作代码(至少是核心代码): -

            try {
                FileInputStream fis = new FileInputStream(dbfile);
                OutputStream backup = new FileOutputStream(backupfilename);

                byte[] buffer = new byte[32768];
                int length;
                while((length = fis.read(buffer)) > 0) {
                    backup.write(buffer, 0, length);
                }
                backup.flush();
                backup.close();
                fis.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }

答案 1 :(得分:0)

我找到了答案,该代码不起作用,因为应用程序的存储权限未打开。它发生在Android版本5 ++

打开设备或虚拟设备上的存储权限。

Application Manager-> {Your App Name} - >权限 - >存储