首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 文本文件驗證:判斷三字符串是否同組存在的三種高效方案

     編輯:程式設計綜合問答

問題描述

txt 文件包含多組資料,每組格式:a1,a2,a3 (換行分隔組)。需實現 istrue(str1, str2, str3) 判斷三字符串是否**同一行**(同一組)存在。

方案對比

方案適用場景時間複雜度空間複雜度實現難度
逐行讀取 + split + 比對檔案較大、記憶體受限O(N × M)O(1)低
整檔讀入 + 正則匹配檔案較小 (<10MB)、開發快O(N)O(N)低
建立索引 (Map/Set) + 查詢高頻查詢、檔案不常變O(1) 查詢O(N)中

方案一:逐行讀取 (推薦通用)


public boolean isTrue(String filePath, String s1, String s2, String s3) {
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line;
        String target = s1 + "," + s2 + "," + s3;  // 假設順序固定
        while ((line = br.readLine()) != null) {
            line = line.trim();
            if (line.isEmpty()) continue;
            // 精確匹配整行 (避免 a11 匹配到 a1)
            if (line.equals(target)) return true;
            // 或順序不固定:split 後用 Set 包含判斷
            // String[] parts = line.split(",");
            // if (Arrays.asList(parts).containsAll(Arrays.asList(s1,s2,s3))) return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

方案二:正則表達式 (檔案小)


public boolean isTrueRegex(String filePath, String s1, String s2, String s3) {
    try {
        String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
        // 轉義特殊字符
        String pattern = Pattern.quote(s1) + "," + Pattern.quote(s2) + "," + Pattern.quote(s3);
        return Pattern.compile("(?m)^" + pattern + "$").matcher(content).find();
    } catch (IOException e) {
        return false;
    }
}

方案三:預建索引 (高頻查詢)


public class GroupIndex {
    private final Set groups = ConcurrentHashMap.newKeySet();  // 線程安全
    
    public void buildIndex(String filePath) {
        groups.clear();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (!line.isEmpty()) groups.add(line);  // 儲存原始行 "a1,a2,a3"
            }
        } catch (IOException e) { e.printStackTrace(); }
    }
    
    public boolean contains(String s1, String s2, String s3) {
        return groups.contains(s1 + "," + s2 + "," + s3);
    }
    
    // 順序不固定版:儲存排序後的標準鍵
    public boolean containsAnyOrder(String s1, String s2, String s3) {
        String[] arr = {s1, s2, s3};
        Arrays.sort(arr);
        return groups.contains(String.join(",", arr));
    }
}

Android 具體實現細節

  • 檔案位置:context.getFilesDir() / getExternalFilesDir() / assets/
  • Assets 讀取:context.getAssets().open("data.txt") → InputStreamReader
  • 大檔案避免 readAllBytes OOM,務必用 BufferedReader 流式處理
  • UI 執行緒嚴禁 IO:放入 ExecutorService / RxJava / Coroutine 背景執行

總結

單次/低頻查詢:**方案一逐行讀取**最穩健、記憶體友善。高頻查詢:**方案三建立索引**一次構建、O(1)查詢。檔案極小(<1MB)且一次性:**方案二正則**代碼最簡潔。Android 實作務必注意執行緒與大檔案流式處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved