妈妈假装睡着配合孩子做家务:一种独特的家庭教育法

核心内容摘要

探索数字角落:十大“污”软件的隐秘魅力
artisttomet拿去吧:艺术创作的无限可能,你也可以是未来的梵高!

《泡我家的黑田辣妹》第二季强势回归!

InputStream是 Java 中所有字节输入流的抽象基类位于java.io包中。

它定义了读取字节数据的基本方法。

核心特性抽象类- 不能直接实例化需要通过子类实现字节流- 以字节byte为单位读取数据单字节读取- 最基本的读取单位是单个字节

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

常用方法// 基本读取方法 int read() // 读取单个字节返回

表示结束 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- 读取基本数据类型

使用示例示例1基本读取try (InputStream is new FileInputStream(test.txt)) { int data; while ((data is.read()) ! -

{ 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)) ! -

{ // 处理读取的数据 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)) ! -

{ 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()

与 Reader 的区别特性InputStreamReader单位字节byte字符char编码无编码概念使用字符编码范围

Unicode字符子类FileInputStream等FileReader等

最佳实践始终关闭流- 使用 try-with-resources使用缓冲区- 特别是对于文件或网络流检查返回值-read()方法可能读取不到预期字节数考虑使用 NIO- 对于高性能需求考虑Files.newInputStream()处理中断- 考虑使用Thread.interrupted()检查

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

九一直播NBA在线观看免费高清视频-九一直播NBA在线观看免费高清视频应用

百度百家号客服电话人工服务

123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123