将文件从Dropbox下载到本地android Java

时间:2014-12-27 10:29:21

标签: java android download local-storage dropbox

我在这段代码上花了几天没有找到解决方案。你能帮帮我吗?

我想将文件从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();

任何想法???

1 个答案:

答案 0 :(得分:1)

我认为您可以使用AsyncTask来实现目标。