亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> java

掌握 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()

示例:逐字节读取文本文件。

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

  1. 深入理解 Java final 关键字:变量、方法与类的不可变性
  2. Java instanceof 运算符完全指南:用法、继承与接口检查
  3. 精通 Java 继承:核心概念、类型与实战示例
  4. 深入理解 Java 静态嵌套类:用法、差异与实战示例
  5. 精通 Java 匿名内部类:定义、语法与实战示例
  6. Java 单例模式详解:安全实现与使用指南
  7. 精通 Java 反射:运行时检查类、方法与字段
  8. 掌握 Java ObjectOutputStream:序列化、核心方法与实战示例
  9. 掌握 Java BufferedReader:高效字符流处理实战指南
  10. 掌握 Java Scanner:读取文本、数字与复杂类型的综合指南
  11. 掌握 Java 泛型:构建可复用、类型安全的代码
  12. 掌握 Java 文件操作:java.io 包下的创建、读取、写入与删除