华硕笔记本优化工具G-Helper:轻量级控制软件全面指南
2026/5/9 8:04:29
InputStream是 Java 中所有字节输入流的抽象基类,位于java.io包中。它定义了读取字节数据的基本方法。
抽象类- 不能直接实例化,需要通过子类实现
字节流- 以字节(byte)为单位读取数据
单字节读取- 最基本的读取单位是单个字节(0-255)
流式访问- 顺序读取,通常不支持随机访问
// 基本读取方法 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() // 是否支持标记/重置FileInputStream fis = new FileInputStream("file.txt");ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);BufferedInputStream bis = new BufferedInputStream(inputStream);ObjectInputStream ois = new ObjectInputStream(inputStream);PipedInputStream- 管道流
SequenceInputStream- 序列流
FilterInputStream- 过滤流基类
DataInputStream- 读取基本数据类型
try (InputStream is = new FileInputStream("test.txt")) { int data; while ((data = is.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); }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(); }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(); }// 推荐使用 try-with-resources try (InputStream is = new FileInputStream("file.txt")) { // 使用流 } // 自动关闭单字节读取性能差,建议使用缓冲区
BufferedInputStream可以显著提升性能
合适的缓冲区大小(通常4KB-8KB)
try { // 读取操作 } catch (IOException e) { // 处理IO异常 } finally { // 确保关闭资源(try-with-resources更优) }不是所有流都支持mark()和reset()
标记有读取限制(readlimit参数)
调用reset()前必须先调用mark()
| 特性 | InputStream | Reader |
|---|---|---|
| 单位 | 字节(byte) | 字符(char) |
| 编码 | 无编码概念 | 使用字符编码 |
| 范围 | 0-255 | Unicode字符 |
| 子类 | FileInputStream等 | FileReader等 |
始终关闭流- 使用 try-with-resources
使用缓冲区- 特别是对于文件或网络流
检查返回值-read()方法可能读取不到预期字节数
考虑使用 NIO- 对于高性能需求,考虑Files.newInputStream()
处理中断- 考虑使用Thread.interrupted()检查
// Java 9 新增 byte[] readAllBytes() // 读取所有字节 long transferTo(OutputStream out) // 直接传输到输出流 // Java 11 新增 byte[] readNBytes(int len) // 精确读取指定数量的字节