java 如何读
读取文件的方法
使用 BufferedReader 读取文本文件:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
读取二进制文件
使用 FileInputStream 读取二进制文件:
try (FileInputStream fis = new FileInputStream("file.bin")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// 处理读取到的数据
}
} catch (IOException e) {
e.printStackTrace();
}
使用 NIO 读取文件
Java NIO 提供更高效的读取方式:
Path path = Paths.get("file.txt");
try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
读取资源文件
从 classpath 读取资源文件:
try (InputStream is = getClass().getResourceAsStream("/resource.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用 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();
}
读取大文件
对于大文件,使用流式处理避免内存溢出:

try (Stream<String> stream = Files.lines(Paths.get("largefile.txt"))) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}






