file Java 读取_Java读取文件方法汇总
时间: 2023-07-18 18:14:31 浏览: 109
好的,下面是Java读取文件的几种常见方法:
1. 使用FileInputStream和BufferedInputStream类:
```java
File file = new File("file.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] contents = new byte[1024];
int bytesRead = 0;
while((bytesRead = bis.read(contents)) != -1) {
System.out.print(new String(contents, 0, bytesRead));
}
```
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. 使用BufferedReader类:
```java
File file = new File("file.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
```
4. 使用Files类:
```java
Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
```
以上是Java读取文件的几种常见方法,你可以根据自己的需求选择适合的方法。
阅读全文