411. Java 文件操作基礎(chǔ) - 從網(wǎng)絡(luò)到本地:讀取文本資源的兩種方式與最佳實(shí)踐
?? 目標(biāo)
- 如何通過
HttpClient API從互聯(lián)網(wǎng)讀取文本資源 - 如何使用
Files API從本地文件讀取 - 如何正確處理 異常 和 資源關(guān)閉
- 如何將
InputStream轉(zhuǎn)換為Reader以便逐行讀取文本
1?? 在線讀?。ㄊ褂?HttpClient)
在有網(wǎng)絡(luò)連接時,可以直接訪問 Gutenberg Project 提供的在線資源。
示例代碼:在線讀取十四行詩
JAVA8
import java.io.*;
import java.net.*;
public class Demo {
public static void main(String[] args) {
String urlStr = "https://www.gutenberg.org/cache/epub/1041/pg1041.txt";
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
System.err.println("HTTP request failed with code: " + responseCode);
return;
}
// 讀取響應(yīng)內(nèi)容,打印前14行
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
String line;
int count = 0;
while ((line = reader.readLine()) != null && count < 14) {
System.out.println(line);
count++;
}
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JAVA11
import java.io.*;
import java.net.URI;
import java.net.http.*;
public class ReadSonnetsOnline {
public static void main(String[] args) {
URI sonnetsURI = URI.create("https://www.gutenberg.org/cache/epub/1041/pg1041.txt");
HttpRequest request = HttpRequest.newBuilder(sonnetsURI)
.GET()
.build();
HttpClient client = HttpClient.newHttpClient();
try {
HttpResponse<InputStream> response =
client.send(request, HttpResponse.BodyHandlers.ofInputStream());
// 將 InputStream 轉(zhuǎn)換為 Reader,便于逐行讀取
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
int count = 0;
while ((line = reader.readLine()) != null && count < 14) {
System.out.println(line);
count++;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
? 要點(diǎn)講解:
-
HttpClient是 Java 11 引入的現(xiàn)代 HTTP 客戶端,替代老舊的HttpURLConnection。 -
HttpResponse.BodyHandlers.ofInputStream()獲取原始字節(jié)流,然后用InputStreamReader轉(zhuǎn)成字符流。 - 使用
try-with-resources確保流在使用后關(guān)閉。 - 示例中只輸出前 14 行,避免刷屏。
2?? 本地讀?。ㄊ褂?Files API)
如果提前下載 pg1041.txt 文件,可以直接用 NIO 的 Files 工具類 來讀取。
示例代碼:本地讀取十四行詩
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.*;
public class ReadSonnetsLocal {
public static void main(String[] args) {
Path path = Path.of("files/sonnets.txt");
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line;
int count = 0;
while ((line = reader.readLine()) != null && count < 14) {
System.out.println(line);
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
? 要點(diǎn)講解:
-
Files.newBufferedReader(path)直接返回一個BufferedReader,方便逐行讀取文本。 - 仍然使用
try-with-resources來自動關(guān)閉資源。 - 整體寫法比
HttpClient更簡單,因為本地文件訪問比網(wǎng)絡(luò)請求更可靠。
3?? 兩種方式對比
| 方式 | 使用場景 | 優(yōu)點(diǎn) | 缺點(diǎn) |
|---|---|---|---|
| HttpClient | 在線讀取 | 不需手動下載,隨時獲取最新內(nèi)容 | 依賴網(wǎng)絡(luò),速度受限 |
| Files API | 本地讀取 | 高效、穩(wěn)定,無需網(wǎng)絡(luò) | 需要事先下載文件 |
4?? 擴(kuò)展思考
如果文件非常大,是否應(yīng)該一次性讀?。?br> ?? 答案:不要。應(yīng)使用 逐行流式讀取,避免內(nèi)存溢出。
-
如果要處理文本編碼(如 UTF-8 / ISO-8859-1)怎么辦?
?? 可以在InputStreamReader或Files.newBufferedReader里指定編碼:new InputStreamReader(response.body(), StandardCharsets.UTF_8); Files.newBufferedReader(path, StandardCharsets.UTF_8);