Eros Live
Find the Way
posts - 15,comments - 0,trackbacks - 0

在程序里备份恢复数据

public static boolean backupDatabase() {
    File dbFile = new File(Environment.getDataDirectory() + "/data/" + PKG + "/databases/" + DB_NAME);
 
    File exportDir = new File(Environment.getExternalStorageDirectory(), "pocket-voa");
    
    if (!exportDir.exists()) {
        exportDir.mkdirs();
    }
    
    File file = new File(exportDir, dbFile.getName());
 
    try {
        file.createNewFile();
        copyFile(dbFile, file);
        return true;
    } catch (IOException e) {
        Log.e(TAG, "[backupDatabase] error", e);
        return false;
    }
}
 
public static boolean restoreDatabase() {
    File dbFile = new File(Environment.getDataDirectory() + "/data/" + PKG + "/databases/" + DatabaseHelper.DB_NAME);
 
    File exportDbFile = new File(Environment.getExternalStorageDirectory() + "/pocket-voa/" + DatabaseHelper.DB_NAME);
    
    if (!exportDbFile.exists())
        return false;
 
    try {
        dbFile.createNewFile();
        copyFile(exportDbFile, dbFile);
        return true;
    } catch (IOException e) {
        Log.e(TAG, "[restoreDatabase] error", e);
        return false;
    }
}
 
private static void copyFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

参考

posted on 2010-07-26 17:24 Eros 阅读(336) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: