java如何取文件
读取文件的方法
在Java中,读取文件可以通过多种方式实现,以下是几种常用的方法:
使用FileInputStream和BufferedReader读取文本文件
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类读取文件内容(Java 7及以上)
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
使用Scanner读取文件
try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException 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();
}
读取文件的其他方式
使用RandomAccessFile随机访问文件
try (RandomAccessFile raf = new RandomAccessFile("file.txt", "r")) {
String line;
while ((line = raf.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用Files.newBufferedReader读取文件(Java 8及以上)

try (BufferedReader br = Files.newBufferedReader(Paths.get("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 文件路径可以是相对路径或绝对路径,确保路径正确。
- 使用
try-with-resources语句确保资源自动关闭。 - 处理异常时,根据实际需求选择合适的异常处理方式。
以上方法涵盖了大多数文件读取场景,可以根据具体需求选择合适的方式。






