代码之家  ›  专栏  ›  技术社区  ›  Rubick

使用动态文件名获取SQLite数据库备份

  •  2
  • Rubick  · 技术社区  · 6 年前

    如果有多个SQLite数据库(在下面的截图中,我想得到11408102018000005)已经备份到了SD卡上 .db 文件?

    注:

    这是图片: enter image description here

    这是我还原SQLite数据库时的代码。

    private void restoreDB() {
        try {
            File[] sd = getContext().getExternalFilesDirs(null);
    
            if (sd[1].canWrite()) {
                File backupDB = new File(sd[1] + "/" + curControlNo);    //<--- what to put here. This is just a test path and name
                File currentDB = new File(getContext().getDatabasePath(DBHelper.DB_NAME).getPath());
    
                FileChannel src = new FileInputStream(backupDB).getChannel();
                FileChannel dst = new FileOutputStream(currentDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Toast.makeText(getContext(), "Import Successful!", Toast.LENGTH_SHORT).show();
                openHome();
            }
        } catch (Throwable e) {
            Toast.makeText(getContext(), "Import Failed!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Vikasdeep Singh    6 年前

    您需要创建文件并传递要保存的数据库名称,如下所示:

    File backupDB = new File(sd[1], DBHelper.DB_NAME); 
    

    希望能成功。

        2
  •  0
  •   MikeT    6 年前

    文件 listFiles 方法若要获取目录中文件的数组,请对该数组进行排序,使最新的文件位于列表的第一位,然后使用该数组的第一个元素。例如

    File[] dirlist = sd.listFiles(); //<<<<<<<< gets the list of files