2016-06-21 64 views
0

我試圖在我的應用程序中運行簡單的數據庫備份,但是當我將設備連接到我的電腦時文件沒有顯示,但似乎沒有問題Android文件管理器。該文件被複制到的方式「下載」文件夾...由我的應用程序複製的文件沒有在電腦上顯示

這裏是我運行復制它的代碼:

//... 
private void backupDatabase(){ 

    String downloadsPath = Environment 
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
      .getAbsolutePath(); 
    String backupDirectoryPath = downloadsPath+"/myapp_backups/"; 
    File backupDirectory = new File(backupDirectoryPath); 
    backupDirectory.mkdirs(); 

    String bkpFileName = "backup_"+(new Date().getTime())+".bkp"; 

    String src = mContext.getDatabasePath(DatabaseHelper.DATABASE_NAME).getAbsolutePath(); 
    String dest = backupDirectoryPath + bkpFileName; 
    FileUtil.copyFile(src, dest); 

} 
//... 

這裏FileUtil.copyFile功能是什麼樣子:

public static boolean copyFile(String src, String dest){ 

    boolean success; 

    try{ 
     if(!isFile(src)){ 
      throw new Exception("Source file doesn't exist: "+src); 
     } 

     InputStream in = new FileInputStream(src); 
     OutputStream out = new FileOutputStream(dest); 

     // Transfer bytes from in to out 
     byte[] buf = new byte[1024]; 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     in.close(); 
     out.close(); 

     success = true; 
    }catch (Exception exception){ 
     exception.printStackTrace(); 
     success = false; 
    } 

    return success; 

} 

該代碼適用於我們測試過的兩個設備,但沒有在PC上顯示該文件。

我失蹤了什麼?

+0

https://stackoverflow.com/questions/32789157/how-to-write-files-to-external-public-storage-in-android-so-那他們是可見的 – CommonsWare

+0

謝謝@CommonsWare,我會看看 – CarlosCarucce

+0

試過重新啓動設備? – andre3wap

回答

0

正如@CommonsWare聯繫的問題所指出的那樣,我對MediaScannerConnection類做了一點研究,並解決了這個問題。

下面是最終代碼:

String downloadsPath = Environment 
     .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
     .getAbsolutePath(); 
String backupDirectoryPath = downloadsPath+"/myapp_backups/"; 
File backupDirectory = new File(backupDirectoryPath); 
backupDirectory.mkdirs(); 

String bkpFileName = "backup_"+(new Date().getTime())+".bkp"; 

String src = mContext.getDatabasePath(DatabaseHelper.DATABASE_NAME).getAbsolutePath(); 
String dest = backupDirectoryPath + bkpFileName; 
FileUtil.copyFile(src, dest); 

//Scan the new file, so it will show up in the PC file explorer: 
MediaScannerConnection.scanFile(
    mContext, new String[]{dest}, null, null 
); 
相關問題