温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java IO中FileInputStream用法

发布时间:2025-12-31 11:13:23 来源:亿速云 阅读:103 作者:小樊 栏目:编程语言

在Java IO中,FileInputStream 是一个用于从文件系统中的某个文件读取字节数据的类。它继承自 InputStream 类,提供了读取原始字节数据的方法。以下是一些常用的 FileInputStream 用法:

创建 FileInputStream 对象

要使用 FileInputStream,首先需要创建一个对象。通常有以下几种方式:

// 创建一个 FileInputStream 对象,读取指定路径的文件
FileInputStream fis = new FileInputStream("path/to/your/file.txt");

// 使用 try-with-resources 语句自动关闭资源
try (FileInputStream fis = new FileInputStream("path/to/your/file.txt")) {
    // 读取文件的代码
}

读取文件内容

FileInputStream 提供了多种方法来读取文件内容,以下是一些常用的方法:

read()

read() 方法从输入流中读取一个字节的数据。返回值是一个介于 0 到 255 之间的整数,表示读取到的字节。如果到达文件末尾,则返回 -1。

int data;
while ((data = fis.read()) != -1) {
    System.out.print((char) data);
}

read(byte[] b)

read(byte[] b) 方法从输入流中读取最多 b.length 个字节的数据,并将它们存储在字节数组 b 中。返回值是实际读取的字节数,如果到达文件末尾,则返回 -1。

byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
    System.out.print(new String(buffer, 0, bytesRead));
}

read(byte[] b, int off, int len)

read(byte[] b, int off, int len) 方法从输入流中读取最多 len 个字节的数据,并将它们存储在字节数组 b 中,从索引 off 开始。返回值是实际读取的字节数,如果到达文件末尾,则返回 -1。

byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer, 0, buffer.length)) != -1) {
    System.out.print(new String(buffer, 0, bytesRead));
}

关闭 FileInputStream

在使用完 FileInputStream 后,需要关闭它以释放系统资源。可以使用 close() 方法来关闭流:

fis.close();

或者使用 try-with-resources 语句自动关闭资源:

try (FileInputStream fis = new FileInputStream("path/to/your/file.txt")) {
    // 读取文件的代码
}

注意:在使用 try-with-resources 语句时,不需要显式调用 close() 方法,因为 Java 会自动关闭资源。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI