如何将数据库还原到其原始目录?

时间:2013-04-03 07:26:59

标签: android sqlite android-sqlite android-sdcard

这是将我的数据保存/复制到SD卡的代码,当我点击备份按钮我的数据库保存在NOTEIT目录中的sdcard时,现在我想恢复这个数据库,当我点击恢复按钮进入我的默认目录所以谁能告诉我如何实现这一目标?

public static void backupDatabase() throws IOException 
{
    try
    {
    File dbFile = new File(Environment.getDataDirectory() + "/data/com.neelrazin.noteit/databases/data");

        File exportDir = new File(Environment.getExternalStorageDirectory()+"/NOTEIT");

        if (!exportDir.exists()) 
        {
            exportDir.mkdirs();
        }

        File file = new File(exportDir, dbFile.getName());

        file.createNewFile();

        FileChannel inChannel = new FileInputStream(dbFile).getChannel();  //fails here

        FileChannel outChannel = new FileOutputStream(file).getChannel();

        try 
        {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } 
        finally 
        {
            if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

我认为还原与备份完全相反。

喜欢这个

public static void restoreDatabase() throws IOException 
{
    try
    {
    File dbFile = new File(Environment.getDataDirectory() + "/data/com.neelrazin.noteit/databases/data");

        File importDir = new File(Environment.getExternalStorageDirectory()+"/NOTEIT");

        if (!importDir.exists()) 
        {
            throw new IOException("External 'NOTEIT' directory does not exist.");
            return;
        }

        File file = new File(importDir, dbFile.getName());
        if (!file.exists()) 
        {
            throw new IOException("Does not exist external db file: NOTEIT/" + dbFile.getName());
            return;
        }

        FileChannel outChannel = new FileOutputStream(dbFile).getChannel();

        FileChannel inChannel = new FileInputStream(file).getChannel();

        try 
        {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } 
        finally 
        {
            if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}