导入/导出Sqlite Db Android时的文件名

时间:2014-12-18 07:27:04

标签: java android

在我的应用程序中,我使用了导入和导出备份功能,但每次因为静态路径而用旧文件替换它?那我怎么解决这个问题

- >在SD卡上导出

public void exportDB(){
    try {

        File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            String currentDBPath = "data/data/com.example.mybudget/databases/MyBudget.db";
            String backupDBPath = sd + "/MyBudget.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(backupDBPath);

            if(sd.exists())
            {
                Toast.makeText(MainActivity.this, "Backup Exists Woult you like to Replace ?", 1000).show();
            }
            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) {
        e.printStackTrace();
    }
}

- - - - >从SD卡导入

public void importDB(){
    try {
        File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            String currentDBPath = sd + "/MyBudget.db";
            String backupDBPath = "data/data/com.example.mybudget/databases/MyBudget.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(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) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将日期添加到文件名中,如下所示:

private static final String DATE_FORMAT_NOW = "yyyyMMddHHmmss";

private String now() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
    return sdf.format(cal.getTime());
}

(...)

String backupDBPath = sd + "/MyBudget-"+now()+".db";

要检索上一个文件,只能按日期(新旧)或按名称排序文件时获取第一个文件(因为日期在名称中)。