2012-07-08 37 views
0

我知道如何搜索文件,但使用特定的路徑,例如/ SD卡/圖片/文件。有沒有辦法搜索該特定的文件。例如:搜索文件。然後,該應用程序將其定位到/ sdcard /圖片中。然後抹掉它。搜索整個SD卡的特定文件

任何幫助?謝謝(我知道如何刪除一個文件,但必須寫完整路徑)

回答

3

可以解決這個問題遞歸地從外部存儲/ SD卡的根目錄開始。

一些未經測試的代碼了我的頭(方法名稱可能是錯的)

public File findFile(File dir, String name) { 
    File[] children = dir.listFiles(); 

    for(File child : children) { 
     if(child.isDirectory()) { 
      File found = findFile(child, name); 
      if(found != null) return found; 
     } else { 
      if(name.equals(child.getName())) return child; 
     } 
    } 

    return null; 
} 

如果你想找到你的SD卡上的所有出現該文件名,你將不得不使用一個列表收集並返回所有找到的匹配項。

+0

嘗試這一個,但getFiles();是java.io.File的未知方法,並且我嘗試說每個我都不能使用java.io.File [] – 2012-07-08 22:25:32

+0

那麼......正如我所說,這是未經測試的代碼,用於說明解決該問題的一般概念遞歸。無論如何。我用正確的函數調用更新了我的示例。 – tiguchi 2012-07-08 22:33:34

+0

好的,謝謝,最後一個問題dir是SD卡嗎?如果不是什麼? – 2012-07-08 23:21:36

0

試試這個:

public class Test { 
    public static void main(String[] args) { 
     File root = new File("/sdcard/"); 
     String fileName = "a.txt"; 
     try { 
      boolean recursive = true; 

      Collection files = FileUtils.listFiles(root, null, recursive); 

      for (Iterator iterator = files.iterator(); iterator.hasNext();) { 
       File file = (File) iterator.next(); 
       if (file.getName().equals(fileName)) 
        System.out.println(file.getAbsolutePath()); 
        file.delete(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

我從FileUtils獲得未知實體 – 2012-07-08 21:59:57

+0

這是因爲上面的示例並非直接針對Android開發。 [FileUtils](http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html)是Apache Commons庫中的一個組件。此外要小心,不要硬編碼到外部存儲器的路徑。無法保證所有設備的外部存儲都安裝在名爲「/ sdcard /」的目錄中。您需要使用[SDK方法](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29)獲取正確的路徑。 – tiguchi 2012-07-08 22:09:36

+0

那麼搜索整個文件呢?即使是電話的? – 2012-07-08 22:18:23