【发布时间】:2014-12-27 18:44:07
【问题描述】:
我在这段代码上花了几天时间却没有找到解决方案。你能帮帮我吗?
我想将文件从 Dropbox 帐户下载到应用程序存储(本地内存)。当我第一次打开文件时,应用程序崩溃了,当我重新启动应用程序时,可以从本地内存中打开文件。
private void ImportDB(String nameDB)
{
try {
File data = Environment.getDataDirectory();
//Local file
String backupDBPath = "//data//[Package name]//databases//"+nameDB;
File backupDB = new File(data, backupDBPath);
//Dropbox file
DbxPath testPath = new DbxPath(DbxPath.ROOT, nameDB);
DbxFileSystem dbxFs = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());
DbxFile testFile = dbxFs.open(testPath);
FileChannel src = testFile.getReadStream().getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
//Transfert to local
dst.transferFrom(src, 0, src.size());
//close
src.close();
dst.close();
testFile.close();
}
catch (Exception e)
{
}
}
我猜这是同步的问题:当我尝试打开文件时,它还没有被复制。我尝试了这段代码来等待文件,但它不起作用,程序停留在 while 循环中:
Thread mThread = new Thread()
{
@SuppressLint("NewApi") @Override
public void run()
{
//open the local file
File data = Environment.getDataDirectory();
String currentDBPath = "//data//[Package name]//databases//"+nameFileDB";
File currentDB = new File(data, currentDBPath);
// test when the file is downloaded
while (!currentDB.exists())
{
Log.i("tag", "In loop");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//CODE TO OPEN THE FILE HERE
}
}
};
mThread.start();
有什么想法???
【问题讨论】:
-
请编辑您的问题并包含来自 logcat 的异常的堆栈跟踪。
-
String backupDBPath = "//data//[Package name]//databases//"+nameDB;实际上是String backupDBPath = "/data/data/[Package name]/databases/" + nameDB;你错过了一个/data...这里也是:String currentDBPath = "//data//[Package name]//databases//"+nameFileDB"; -
感谢您的回答,但这不是路径问题,因为当我重新启动应用程序(第一次崩溃后)时,它可以使用此路径打开本地内存中的文件://data //[包名]//数据库//"+nameDB
-
其实要严谨一点,我们可以通过getApplicationContext().getDatabasePath(nameDB).getPath()改变 //data//[Package name]//databases//"+nameFileDB"
标签: java android download local-storage dropbox