掌握 Java FileInputStream:核心方法与实战代码示例全解析
Java FileInputStream 类
FileInputStream 位于 java.io,用于从文件读取原始字节数据。继承抽象 InputStream,提供文件 I/O 具体实现。
创建 FileInputStream
导入类后用文件路径或 File 对象实例化。
1. 使用文件路径
FileInputStream input = new FileInputStream("path/to/file.txt");
2. 使用 File 对象
File file = new File("file.txt");
FileInputStream input = new FileInputStream(file);
FileInputStream 关键方法
read()
int read()– 读单字节,返回int(EOF 返回-1)int read(byte[] b)– 填充字节数组int read(byte[] b, int off, int len)– 从偏移off读最多len字节到b
示例:逐字节读取文本文件。
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try (FileInputStream input = new FileInputStream("input.txt")) {
System.out.println("Data in the file:");
int byteRead;
while ((byteRead = input.read()) != -1) {
System.out.print((char) byteRead);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出
Data in the file: This is a line of text inside the file.
available()
返回无阻塞可读字节数。
try (FileInputStream input = new FileInputStream("input.txt")) {
System.out.println("Available at start: " + input.available());
input.read(); input.read(); input.read();
System.out.println("Available after 3 reads: " + input.available());
}
输出
Available at start: 39 Available after 3 reads: 36
skip()
按指定字节数前移流位置并丢弃。
try (FileInputStream input = new FileInputStream("input.txt")) {
input.skip(5); // 跳过 "This "
int byteRead;
while ((byteRead = input.read()) != -1) {
System.out.print((char) byteRead);
}
}
输出
is a line of text inside the file.
close()
关闭流释放资源。try-with-resources 确保自动调用。
FileInputStream 其他方法
| 方法 | 描述 |
|---|---|
finalize() | 垃圾回收前确保调用 close() |
getChannel() | 返回关联的 FileChannel |
getFD() | 获取底层文件描述符 |
mark(int readlimit) | 标记当前位置供重置 |
reset() | 重置到最近标记位置 |
详见官方文档:Java FileInputStream。
java
- 深入理解 Java final 关键字:变量、方法与类的不可变性
- Java instanceof 运算符完全指南:用法、继承与接口检查
- 精通 Java 继承:核心概念、类型与实战示例
- 深入理解 Java 静态嵌套类:用法、差异与实战示例
- 精通 Java 匿名内部类:定义、语法与实战示例
- Java 单例模式详解:安全实现与使用指南
- 精通 Java 反射:运行时检查类、方法与字段
- 掌握 Java ObjectOutputStream:序列化、核心方法与实战示例
- 掌握 Java BufferedReader:高效字符流处理实战指南
- 掌握 Java Scanner:读取文本、数字与复杂类型的综合指南
- 掌握 Java 泛型:构建可复用、类型安全的代码
- 掌握 Java 文件操作:java.io 包下的创建、读取、写入与删除