Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 檔案搜尋實作:在 SD 卡中遞迴查找指定檔名

編輯:Android 開發實例

做檔案管理器或需要掃描外部儲存空間時,「找出所有符合關鍵字的檔案」幾乎是必備功能。本文示範一個簡潔的實作:使用者輸入搜尋目錄與關鍵字,程式遞迴走訪底下所有子目錄,把命中的完整路徑列出來。

實作成果

介面由上而下是:搜尋起點的輸入欄(預設根目錄 /)、關鍵字輸入欄、一顆「開始搜尋」按鈕,以及一個用來輸出結果清單的 TextView。

一、版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="/" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <TextView
            android:text="輸入檔案名稱:"
            android:textSize="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/editText1"
            android:textSize="20dp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="開始搜尋" />

    <TextView
        android:id="@+id/textView1"
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

二、比對邏輯:indexOf 就夠了

判斷檔名是否符合條件,用 File.getName().indexOf(keyword) >= 0 就能做到「包含即符合」;若想不分大小寫,先 toLowerCase() 再比對。

for (File f : files) {
    if (f.getName().toLowerCase().contains(keyword.toLowerCase())) {
        res += f.getPath() + "\n";
    }
}

listFiles() 取得某目錄底下所有項目,再用 for-each 逐一走訪,這是最直白的寫法。

三、完整程式:加上遞迴才能真正找得深

原例只掃一層目錄,實用性有限。把它改成遞迴,就能把整棵子目錄樹都走過:

package net.javablog.mobile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity {

    private TextView textView1;
    private EditText editText1;   // 關鍵字
    private EditText editText2;   // 搜尋起點
    private Button button1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textView1 = (TextView) findViewById(R.id.textView1);
        editText1 = (EditText) findViewById(R.id.editText1);
        editText2 = (EditText) findViewById(R.id.editText2);
        button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String keyword = editText1.getText().toString().trim();
                File root = new File(editText2.getText().toString());

                if (!root.isDirectory()) {
                    textView1.setText("不是有效的目錄");
                    return;
                }
                if (keyword.isEmpty()) {
                    textView1.setText("請輸入關鍵字");
                    return;
                }

                List<String> hits = new ArrayList<String>();
                findFile(root, keyword.toLowerCase(), hits);

                if (hits.isEmpty()) {
                    textView1.setText("沒有找到相關檔案");
                } else {
                    StringBuilder sb = new StringBuilder();
                    for (String path : hits) {
                        sb.append(path).append("\n");
                    }
                    textView1.setText(sb.toString());
                }
            }
        });
    }

    /** 遞迴走訪:符合關鍵字就收集,是目錄就繼續往下找 */
    private void findFile(File dir, String keyword, List<String> result) {
        File[] files = dir.listFiles();
        if (files == null) return;      // 無權限或讀取失敗

        for (File f : files) {
            if (f.isDirectory()) {
                findFile(f, keyword, result);
            } else if (f.getName().toLowerCase().contains(keyword)) {
                result.add(f.getPath());
            }
        }
    }
}

四、實務上會踩到的幾個坑

  • 權限:讀取外部儲存空間需要宣告並請求讀取權限;Android 11 以後若要廣泛存取檔案,得走 MediaStore 或儲存空間存取架構(SAF),不再是天經地義就能讀根目錄。
  • listFiles() 可能回傳 null:目錄不存在、不是目錄或無權限時都會回 null,務必先判斷再走訪,否則直接 NullPointerException。
  • 別在 UI 執行緒上跑:遞迴掃描整個 SDCard 動輒上千檔案,放在 onClick() 裡會讓畫面凍住甚至 ANR。應移到背景執行緒,用 runOnUiThread() 或 Handler 回推結果。
  • 用 StringBuilder 組字串:迴圈中以 += 串接會產生大量臨時物件,改用 StringBuilder 或收集到 List 再一次顯示。
  • 大量結果要分頁:命中幾百筆時,TextView 一次塞完會拖慢繪製,改用 ListView/RecyclerView 呈現並支援捲動。

這題示範的是最基礎的檔案樹遍歷,程式碼短,但把權限、例外、執行緒與效能四個面向一併想清楚,就已經是可直接用在專案裡的樣子了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved