在本教程中,我们将借助示例学习Java FileInputStream及其方法。
java.io包的FileInputStream类可用于从文件中读取数据(以字节为单位)。
它继承了InputStream抽象类。

在学习之前FileInputStream,请确保已经了解Java File(文件)。
为了创建文件输入流,我们必须首先导入java.io.FileInputStream包。导入包后,就可以使用Java创建文件输入流。
1.使用文件路径
FileInputStream input = new FileInputStream(stringPath);
在这里,我们创建了一个输入流,该输入流将链接到所指定的文件路径。
2.使用文件的对象
FileInputStream input = new FileInputStream(File fileObject);
在这里,我们创建了一个输入流,该输入流将链接到由fileObject指定的文件。
FileInputStream类为InputStream类中出现的不同方法提供了实现。
read() - 从文件中读取一个字节
read(byte[] array) - 从文件中读取字节并存储在指定的数组中
read(byte[] array, int start, int length) - 从文件中读取等于length的字节数,并从位置start开始存储在指定的数组中
假设我们有一个名为input.txt的文件,其中包含以下内容。
This is a line of text inside the file.
让我们尝试使用FileInputStream读取此文件。
import java.io.FileInputStream;
public class Main {
public static void main(String args[]) {
try {
FileInputStream input = new FileInputStream("input.txt");
System.out.println("文件中的数据: ");
//读取第一个字节
int i = input.read();
while(i != -1) {
System.out.print((char)i);
//从文件中读取下一个字节
i = input.read();
}
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}输出结果
文件中的数据: This is a line of text inside the file.
在上面的示例中,我们创建了一个名为input的文件输入流。输入流与input.txt文件链接。
FileInputStream input = new FileInputStream("input.txt");为了从文件中读取数据,我们在while循环中使用了read()方法。
要获取可用字节数,我们可以使用available()方法。例如,
import java.io.FileInputStream;
public class Main {
public static void main(String args[]) {
try {
//假设input.txt文件包含以下文本
//这是文件中的一行文本。
FileInputStream input = new FileInputStream("input.txt");
//返回可用字节数
System.out.println("开始时可用的字节数: " + input.available());
//从文件中读取3个字节
input.read();
input.read();
input.read();
//返回可用字节数
System.out.println("结束时的可用字节数: " + input.available());
input.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}输出结果
开始时可用的字节数: 39 结束时的可用字节数: 36
在以上示例中,
我们首先使用available()方法检查文件输入流中的可用字节数。
然后,我们已经使用read()方法3次从文件输入流中读取3个字节。
现在,在读取字节之后,我们再次检查了可用字节。这次,可用字节减少了3。
要丢弃和跳过指定的字节数,可以使用skip()方法。例如
import java.io.FileInputStream;
public class Main {
public static void main(String args[]) {
try {
//假设input.txt文件包含以下文本
//这是文件中的一行文本。
FileInputStream input = new FileInputStream("input.txt");
//跳过5个字节
input.skip(5);
System.out.println("输入流跳过5个字节:");
//读取第一个字节
int i = input.read();
while (i != -1) {
System.out.print((char) i);
//从文件中读取下一个字节
i = input.read();
}
// close() 方法
input.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}输出结果
输入流跳过5个字节: is a line of text inside the file.
在上面的示例中,我们使用了skip()方法从文件输入流中跳过5个字节的数据。因此,不会从输入流中读取表示文本“ This”的字节。
要关闭文件输入流,可以使用close()方法。一旦close()方法被调用,我们就不能使用输入流来读取数据。
在以上所有示例中,我们都使用了close()方法来关闭文件输入流。
| 方法 | 内容描述 |
|---|---|
| finalize() | 确保close()方法被调用 |
| getChannel() | 返回FileChannel与输入流关联的对象 |
| getFD() | 返回与输入流关联的文件描述符 |
| mark() | 标记输入流中已读取数据的位置 |
| reset() | 将控件返回到输入流中设置了标记的点 |