下載 Android 官方文檔離線包(docs-*.zip)後,本地用瀏覽器開啟 index.html 卻極度緩慢、甚至卡死。原因在於 HTML 仍包含指向 Google 伺服器的外部資源:
fonts.googleapis.com/css?family=Roboto+Condensed、fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,boldwww.google.com/jsapideveloper.android.com/ytblogger_lists_unified.js瀏覽器嘗試下載這些資源,受限於網路環境導致長時間阻塞渲染。
編寫一個遞迴掃描工具,將所有 HTML 檔案中的上述外部連結完全移除(替換為空字串),保留本地相對路徑資源,實現真正離線秒開。
package com.example.androiddoc;
import java.io.*;
import java.nio.file.*;
public class AndroidDocCleaner {
// 需移除的外部資源片段(精確匹配,含屬性值)
private static final String[] TARGETS = {
"<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto+Condensed\">",
"<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold\" title=\"roboto\">",
"<script src=\"https://www.google.com/jsapi\" type=\"text/javascript\"></script>",
"<script src=\"https://developer.android.com/ytblogger_lists_unified.js\" type=\"text/javascript\"></script>"
};
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("用法: java AndroidDocCleaner <文檔根目錄>");
return;
}
Path root = Paths.get(args[0]);
if (!Files.isDirectory(root)) {
System.err.println("目錄不存在: " + root);
return;
}
cleanDirectory(root);
System.out.println("清理完成!");
}
private static void cleanDirectory(Path dir) throws IOException {
try (var stream = Files.walk(dir)) {
stream.filter(p -> p.toString().endsWith(".html"))
.forEach(AndroidDocCleaner::cleanFile);
}
}
private static void cleanFile(Path file) {
try {
String content = Files.readString(file);
boolean changed = false;
for (String target : TARGETS) {
if (content.contains(target)) {
content = content.replace(target, "");
changed = true;
}
}
if (changed) {
Files.writeString(file, content);
System.out.println("已清理: " + file);
}
} catch (IOException e) {
System.err.println("處理失敗: " + file + " - " + e.getMessage());
}
}
}
D:\android-docs)。javac AndroidDocCleaner.javajava AndroidDocCleaner D:\android-docsindex.html,享受流暢離線閱讀。Pattern.compile("<link[^>]*fonts\\.googleapis\\.com[^>]*>") 等模式匹配。_backup,防誤刪。Files.walk(...).parallelStream() 加速。fonts/,並修改 CSS @font-face 指向本地路徑,保持視覺一致性。擴充功能僅攔截網路請求,HTML 仍包含外部連結標籤,解析 DOM 仍有微小開銷;徹底移除標籤才是根治。此外,此方案適用於無 GUI 環境(伺服器、CI/CD 打包流程)。
一鍵執行,告別卡頓,專注學習 Android 開發!