gpt4 book ai didi

android - 如何将数据库恢复到原始目录?

转载 作者:行者123 更新时间:2023-12-02 07:13:13 25 4
gpt4 key购买 nike

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

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();
}
}

最佳答案

我相信恢复与备份完全相反。

像这样:

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();
}
}

关于android - 如何将数据库恢复到原始目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15781299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com