java如何读取文字
读取文本文件的方法
使用 BufferedReader 和 FileReader 可以逐行读取文本文件内容。这种方法适合处理大文件,避免一次性加载全部内容。
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
读取整个文件内容
Files.readAllLines 方法可以一次性读取所有行到列表中,适用于小文件。

List<String> lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
使用 Scanner 读取
Scanner 类提供更灵活的文本解析功能,可以按特定分隔符读取内容。

try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
读取资源文件
从类路径资源中读取文件,适用于打包在 JAR 中的资源。
try (InputStream is = getClass().getResourceAsStream("/resource.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
处理字符编码
指定字符编码防止乱码,推荐使用 UTF-8。
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream("file.txt"), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}






