2

这是将我的数据保存/复制到 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();
    }
}
4

1 回答 1

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();
    }
}
于 2013-04-03T07:44:04.823 回答