怎么用java fileinputstream读取文件

1162
2023/9/27 10:27:31
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要使用Java FileInputStream读取文件,可以按照以下步骤进行操作:

  1. 创建一个FileInputStream对象,并将要读取的文件路径作为参数传递给它。例如:
FileInputStream fis = new FileInputStream("文件路径");
  1. 创建一个缓冲区数组,用来存储从文件中读取的数据。例如:
byte[] buffer = new byte[1024];
  1. 使用read()方法从文件中读取数据,并将其存储在缓冲区数组中。read()方法返回读取的字节数,如果已到达文件末尾,则返回-1。例如:
int bytesRead = fis.read(buffer);
  1. 使用while循环遍历缓冲区数组中的数据,直到读取的字节数为-1,表示已到达文件末尾。例如:
while (bytesRead != -1) {
// 处理读取到的数据
// ...
// 继续读取数据
bytesRead = fis.read(buffer);
}
  1. 关闭FileInputStream对象,释放资源。例如:
fis.close();

下面是一个完整的示例,演示如何使用FileInputStream读取文件并将内容输出到控制台:

import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("文件路径");
byte[] buffer = new byte[1024];
int bytesRead = fis.read(buffer);
while (bytesRead != -1) {
for (int i = 0; i < bytesRead; i++) {
System.out.print((char) buffer[i]);
}
bytesRead = fis.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

请将代码中的"文件路径"替换为您要读取的文件路径。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中listnode的作用是什么