java基础-InputStream 类
2026/5/9 8:04:56 网站建设 项目流程

InputStream是 Java 中所有字节输入流的抽象基类,位于java.io包中。它定义了读取字节数据的基本方法。

一、核心特性

  1. 抽象类- 不能直接实例化,需要通过子类实现

  2. 字节流- 以字节(byte)为单位读取数据

  3. 单字节读取- 最基本的读取单位是单个字节(0-255)

  4. 流式访问- 顺序读取,通常不支持随机访问

二、常用方法

// 基本读取方法 int read() // 读取单个字节,返回0-255,-1表示结束 int read(byte[] b) // 读取到字节数组,返回实际读取字节数 int read(byte[] b, int off, int len) // 读取指定长度到数组的指定位置 // 其他重要方法 long skip(long n) // 跳过指定字节数 int available() // 返回可读取的字节数(估计值) void close() // 关闭流,释放资源 void mark(int readlimit) // 标记当前位置 void reset() // 重置到标记位置 boolean markSupported() // 是否支持标记/重置

三、主要子类

1. 文件输入流

FileInputStream fis = new FileInputStream("file.txt");

2. 字节数组输入流

ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);

3. 缓冲输入流(装饰器)

BufferedInputStream bis = new BufferedInputStream(inputStream);

4. 对象输入流(反序列化)

ObjectInputStream ois = new ObjectInputStream(inputStream);

5. 其他子类

  • PipedInputStream- 管道流

  • SequenceInputStream- 序列流

  • FilterInputStream- 过滤流基类

  • DataInputStream- 读取基本数据类型

四、使用示例

示例1:基本读取

try (InputStream is = new FileInputStream("test.txt")) { int data; while ((data = is.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); }

示例2:使用缓冲区读取

try (InputStream is = new FileInputStream("largefile.bin"); BufferedInputStream bis = new BufferedInputStream(is)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { // 处理读取的数据 processData(buffer, bytesRead); } } catch (IOException e) { e.printStackTrace(); }

示例3:读取到字节数组

public static byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, bytesRead); } return buffer.toByteArray(); }

五、重要注意事项

1.资源管理

// 推荐使用 try-with-resources try (InputStream is = new FileInputStream("file.txt")) { // 使用流 } // 自动关闭

2.读取性能

  • 单字节读取性能差,建议使用缓冲区

  • BufferedInputStream可以显著提升性能

  • 合适的缓冲区大小(通常4KB-8KB)

3.异常处理

try { // 读取操作 } catch (IOException e) { // 处理IO异常 } finally { // 确保关闭资源(try-with-resources更优) }

4.标记/重置限制

  • 不是所有流都支持mark()reset()

  • 标记有读取限制(readlimit参数)

  • 调用reset()前必须先调用mark()

六、与 Reader 的区别

特性InputStreamReader
单位字节(byte)字符(char)
编码无编码概念使用字符编码
范围0-255Unicode字符
子类FileInputStream等FileReader等

七、最佳实践

  1. 始终关闭流- 使用 try-with-resources

  2. 使用缓冲区- 特别是对于文件或网络流

  3. 检查返回值-read()方法可能读取不到预期字节数

  4. 考虑使用 NIO- 对于高性能需求,考虑Files.newInputStream()

  5. 处理中断- 考虑使用Thread.interrupted()检查

八、Java 9+ 新增方法

// Java 9 新增 byte[] readAllBytes() // 读取所有字节 long transferTo(OutputStream out) // 直接传输到输出流 // Java 11 新增 byte[] readNBytes(int len) // 精确读取指定数量的字节

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询