用java写一个文件读取功能,具体怎么实现
时间: 2023-07-18 22:16:07 浏览: 41
文件读取功能在Java中可以使用FileInputStream或者BufferedReader来实现,以下是两种方法的示例代码:
1. 使用FileInputStream读取文件内容:
```java
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("file.txt");
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
fis.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
```
2. 使用BufferedReader读取文件内容:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
```
其中,第一种方法使用FileInputStream读取文件内容,每次只能读取一个字节,需要使用while循环逐个读取,速度较慢;第二种方法使用BufferedReader读取文件内容,可以一次读取一行,速度较快。使用哪种方法取决于文件的大小和读取的需求。