核心步驟
- 獲取類加載器資源 URL:
Class.getResource("/path")
- URL 解碼處理中文路徑:
URLDecoder.decode(url.getFile(), "UTF-8")
- 構建
File 對象
- 使用
FileInputStream + InputStreamReader + BufferedReader 按行讀取
完整代碼
public static void readClasspathFile() {
// 1. 獲取資源 URL(假設文件在 src/main/resources/simu/test.txt)
String path = Test.class.getResource("/simu").getFile();
try {
// 2. URL 解碼(處理空格、中文等特殊字符)
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
System.out.println("文件路徑: " + path);
// 3. 構建 File
File file = new File(path, "test.txt");
// 4. 字節流 -> 字符流 -> 緩衝流
InputStream is = null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) { e.printStackTrace(); }
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) { e.printStackTrace(); }
System.out.println("文件內容:\n" + sb.toString());
}
關鍵點提示
getResource("") 返回目錄 URL,getResource("file.txt") 返回文件 URL
- JAR 包中文件無法用
File 訪問,需用 getResourceAsStream() 直接獲取輸入流
- 指定
StandardCharsets.UTF_8 避免平台默認編碼不一致
try-with-resources (Java 7+) 自動關閉流,簡化 finally 塊
改進版:兼容 JAR 包
public static String readResource(String resourcePath) throws IOException {
try (InputStream is = Test.class.getResourceAsStream(resourcePath);
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append("\n");
return sb.toString();
}
}