java中如何读取文件
读取文件的方法
在Java中,读取文件可以通过多种方式实现,具体取决于文件类型和需求。以下是几种常见的方法:
使用FileReader和BufferedReader
这种方法适合逐行读取文本文件。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Files类(Java 7及以上)
Files类提供了便捷的方法读取文件内容,适合小文件。
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(filePath));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Scanner类
Scanner类适合按特定分隔符读取文件内容。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (Scanner scanner = new Scanner(new File(filePath))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
使用InputStream和BufferedReader
适合读取二进制文件或文本文件。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 文件路径可以是相对路径或绝对路径。
- 使用try-with-resources语句确保资源自动关闭。
- 处理IO异常以避免程序崩溃。
以上方法覆盖了大多数文件读取场景,根据具体需求选择合适的方式。







