将SQLite数据库备份到SD卡

时间:2017-05-11 08:41:27

标签: android sqlite

我试图将我的sqlite数据库备份到我的SD卡,我试图按照This方式但我无法在我的SD卡中找到数据库。我做错了什么?

public void exportDatabse(String DBOperations) {

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//com.example.hp.semakoperasimampatansrc//databases//attendant_info.db";
            String backupDBPath = "attendant_info_backup.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
    }

我如何调用该方法:

db.exportDatabse("attendant_info.db");

我也添加了

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

到我的清单

3 个答案:

答案 0 :(得分:2)

您可以通过以下方式执行此操作,这不仅可以用于复制数据库,还可以用于复制文件和共享pref(如果有)。创建一个名为 DeveloperOption 的类,并使用其方法 copyAppDataToLocal 来执行此操作。

如果目标sdk为23或以上

,则需要运行时权限
//package declaration
import android.app.Activity;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class DeveloperOption {
    public static final String BASE_PATH = Environment.getExternalStoragePublicDirectory
            ("App_BackUp").getAbsolutePath();
    public static final String SEPARATOR = "/";
    private static boolean operationStatus = true;
    private static String dataDirectory = null;
    private static String appName = "APP_NAME";

    public static boolean copyAppDataToLocal(Activity callingActivity, String appName) {

        dataDirectory = callingActivity.getApplicationInfo().dataDir;
        DeveloperOption.appName = appName;
        String TAG = "Developer_Option";
        try {
            if(dataDirectory != null) {
                copyAppData(new File(dataDirectory, "shared_prefs"),"shared_prefs");
                copyAppData(new File(dataDirectory, "files"),"files");
                copyAppData(new File(dataDirectory, "databases"),"databases");
            } else {
                Log.e(TAG, "!!!!!Unable to get data directory for ACTIVITY-->" + callingActivity
                        .toString());
            }
        } catch (Exception ex) {
            Log.e(TAG, "!!!!@@@Exception Occurred while copying DATA--->"+ex.getMessage(),ex.fillInStackTrace());
            operationStatus = false;
        }

        return operationStatus;
    }

    private static void copyFileToStorage(String directoryName, String inFile, String fileName, boolean
            isDirectory, String subdirectoryName) {
        try {
            FileInputStream myInput = new FileInputStream(inFile);
            File out_dir;
            if(!isDirectory) {
                out_dir = new File(BASE_PATH+ SEPARATOR + appName +
                        SEPARATOR + directoryName);
            } else {
                out_dir = new File(BASE_PATH + SEPARATOR + appName +
                        SEPARATOR + directoryName + SEPARATOR + subdirectoryName);
            }
            if(!out_dir.exists()) {
                operationStatus = out_dir.mkdirs();
            }
            String outFileName = out_dir + "/" + fileName;
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte[] buffer1 = new byte[1024];
            int length;
            while ((length = myInput.read(buffer1)) > 0) {
                myOutput.write(buffer1, 0, length);
            }
            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void copyAppData(File fileTypeToBeCopied, String outDirectoryName){
        if(fileTypeToBeCopied.exists() && fileTypeToBeCopied.isDirectory()) {
            File[] files = fileTypeToBeCopied.listFiles();
            for (File file : files) {
                if(file.isFile()) {
                    copyFileToStorage(outDirectoryName, file.getAbsolutePath(), file.getName(), false, "");
                } else {
                    String folderName = file.getName();
                    File databaseDirsNew = new File(dataDirectory, outDirectoryName+"/" + folderName);
                    if(databaseDirsNew.exists() && databaseDirsNew.isDirectory()) {
                        File[] filesDB = databaseDirsNew.listFiles();
                        for (File file1 : filesDB) {
                            if(file1.isFile()) {
                                copyFileToStorage(outDirectoryName, file1.getAbsolutePath(), file1.getName(),
                                        true, folderName);
                            }
                        }
                    }
                }
            }
        }
    }
}

答案 1 :(得分:0)

尝试为Android 6.0(API级别23)及更高级别from official docs

添加运行时权限请求

获取WRITE_EXTERNAL_STORAGE权限的代码

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1 && !checkIfAlreadyhavePermission()) {
        requestForSpecificPermission();
    }

private boolean checkIfAlreadyhavePermission() {
    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        return false;
    }
    return true;
}

请求像这样的其他许可

private void requestForSpecificPermission() {
    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
}

答案 2 :(得分:0)

  

试试这个。

public void exportDatabse(String DBOperations){
    File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String currentDBPath = "//data//com.example.hp.semakoperasimampatansrc//databases//attendant_info.db";
       String backupDBPath = DBOperations;
       File currentDB = new File(data, currentDBPath);
       File backupDB = new File(sd, backupDBPath);
       try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
        } catch(IOException e) {
            e.printStackTrace();
        }
}