使用FileInputStream循环读文件
时间: 2024-02-02 17:09:14 浏览: 69
使用FileInputStream循环读取文件的步骤如下:
1. 创建FileInputStream对象并指定要读取的文件路径。
2. 创建一个字节数组来存储读取的数据。
3. 使用循环结构,每次从输入流中读取一定数量的字节到字节数组中。
4. 判断读取的字节数,如果为-1,则表示已经读取到文件末尾,退出循环。
5. 将读取到的字节数组转换为字符串并输出。
6. 关闭输入流。
以下是一个示例代码:
```java
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamDemo {
public static void main(String[] args) {
FileInputStream file = null;
try {
file = new FileInputStream("E:\\app\\ideaProject\\IO_liu\\FileInputStreamDemo.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = file.read(buffer)) != -1) {
String content = new String(buffer, 0, bytesRead);
System.out.print(content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
请注意,上述代码中的文件路径需要根据实际情况进行修改。
阅读全文
相关推荐


















