java readfile_Java读取文件的四种方法
时间: 2024-02-01 17:16:36 浏览: 202
Java读取文件的四种方法:
1. 使用FileReader和BufferedReader类读取文件
```java
File file = new File("file.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fr.close();
```
2. 使用Scanner类读取文件
```java
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
```
3. 使用Files类读取文件
```java
Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
```
4. 使用InputStream和BufferedInputStream类读取文件
```java
File file = new File("file.txt");
InputStream is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, len));
}
bis.close();
is.close();
```
阅读全文