Java 的 I/O 流是什么?

📅 发布时间:2026/7/15 8:37:33 👁️ 浏览次数:
Java 的 I/O 流是什么?
Java 的 I/O 流Input/Output Stream是 Java 中用于处理输入和输出操作的核心机制。它提供了一种统一的方式来读取和写入数据无论数据源是文件、网络连接、内存还是其他设备。I/O 流的基本概念I/O 流可以看作是数据的流动管道输入流从数据源读取数据到程序中输出流从程序写入数据到目标位置I/O 流的分类体系1.按数据流向分类// 输入流 - 读取数据InputStream,Reader// 输出流 - 写入数据OutputStream,Writer2.按数据类型分类// 字节流 - 处理二进制数据8位字节InputStream,OutputStream// 字符流 - 处理文本数据16位字符Reader,Writer主要 I/O 流类字节流Byte StreamsInputStream 常用子类FileInputStream// 从文件读取字节ByteArrayInputStream// 从字节数组读取BufferedInputStream// 带缓冲的输入流DataInputStream// 读取基本数据类型ObjectInputStream// 读取对象序列化OutputStream 常用子类FileOutputStream// 向文件写入字节ByteArrayOutputStream// 向字节数组写入BufferedOutputStream// 带缓冲的输出流DataOutputStream// 写入基本数据类型ObjectOutputStream// 写入对象序列化PrintStream// 格式化输出字符流Character StreamsReader 常用子类FileReader// 从文件读取字符CharArrayReader// 从字符数组读取BufferedReader// 带缓冲的字符输入流InputStreamReader// 字节流到字符流的桥梁Writer 常用子类FileWriter// 向文件写入字符CharArrayWriter// 向字符数组写入BufferedWriter// 带缓冲的字符输出流OutputStreamWriter// 字符流到字节流的桥梁PrintWriter// 格式化字符输出基本使用示例1.文件复制字节流try(InputStreaminnewFileInputStream(source.txt);OutputStreamoutnewFileOutputStream(target.txt)){byte[]buffernewbyte[1024];intbytesRead;while((bytesReadin.read(buffer))!-1){out.write(buffer,0,bytesRead);}}2.文本文件读写字符流// 读取文本文件try(BufferedReaderreadernewBufferedReader(newFileReader(input.txt))){Stringline;while((linereader.readLine())!null){System.out.println(line);}}// 写入文本文件try(BufferedWriterwriternewBufferedWriter(newFileWriter(output.txt))){writer.write(Hello, World!);writer.newLine();writer.write(这是第二行);}3.带缓冲的高效读写// 高效文件复制try(BufferedInputStreambisnewBufferedInputStream(newFileInputStream(source.jpg));BufferedOutputStreambosnewBufferedOutputStream(newFileOutputStream(target.jpg))){byte[]buffernewbyte[8192];// 8KB缓冲区intbytesRead;while((bytesReadbis.read(buffer))!-1){bos.write(buffer,0,bytesRead);}}高级特性1.装饰器模式Java I/O 使用装饰器模式可以灵活组合功能// 多层包装每层添加不同功能DataInputStreamdisnewDataInputStream(newBufferedInputStream(newFileInputStream(data.bin)));2.序列化与反序列化// 对象序列化写入try(ObjectOutputStreamoosnewObjectOutputStream(newFileOutputStream(user.dat))){UserusernewUser(张三,25);oos.writeObject(user);}// 对象反序列化读取try(ObjectInputStreamoisnewObjectInputStream(newFileInputStream(user.dat))){Useruser(User)ois.readObject();System.out.println(user.getName());}3.NIONew I/OJava NIO 提供了更高效的 I/O 操作// 使用 NIO 进行文件复制PathsourcePaths.get(source.txt);PathtargetPaths.get(target.txt);Files.copy(source,target,StandardCopyOption.REPLACE_EXISTING);// 使用 Channel 和 Buffertry(FileChannelinChannelFileChannel.open(source);FileChanneloutChannelFileChannel.open(target,StandardOpenOption.CREATE,StandardOpenOption.WRITE)){ByteBufferbufferByteBuffer.allocate(8192);while(inChannel.read(buffer)!-1){buffer.flip();// 切换为读模式outChannel.write(buffer);buffer.clear();// 清空缓冲区}}try-with-resources 自动资源管理Java 7 引入的 try-with-resources 语法确保流正确关闭// 传统方式需要手动关闭FileInputStreamfisnull;try{fisnewFileInputStream(file.txt);// 使用流}finally{if(fis!null){fis.close();// 必须手动关闭}}// try-with-resources自动关闭try(FileInputStreamfisnewFileInputStream(file.txt);FileOutputStreamfosnewFileOutputStream(output.txt)){// 使用流自动关闭}实际应用场景1.配置文件读取PropertiespropsnewProperties();try(InputStreamisgetClass().getResourceAsStream(/config.properties)){props.load(is);Stringurlprops.getProperty(database.url);}2.网络通信// 简单的 HTTP 客户端try(SocketsocketnewSocket(example.com,80);PrintWriteroutnewPrintWriter(socket.getOutputStream(),true);BufferedReaderinnewBufferedReader(newInputStreamReader(socket.getInputStream()))){out.println(GET / HTTP/1.1);out.println(Host: example.com);out.println();Stringresponse;while((responsein.readLine())!null){System.out.println(response);}}3.数据加密传输// 使用加密流try(CipherInputStreamcisnewCipherInputStream(newFileInputStream(encrypted.dat),cipher);ObjectInputStreamoisnewObjectInputStream(cis)){SecretDatadata(SecretData)ois.readObject();}性能优化建议使用缓冲流BufferedInputStream/BufferedOutputStream提高性能合理设置缓冲区大小通常 4KB-8KB 为宜及时关闭流使用 try-with-resources 避免资源泄漏考虑使用 NIO对于高并发场景NIO 性能更好批量操作尽量使用数组进行批量读写总结Java I/O 流的主要特点统一的接口所有 I/O 操作都基于流的概念灵活的扩展通过装饰器模式组合不同功能类型安全字节流和字符流明确区分资源管理try-with-resources 确保资源正确释放高性能缓冲机制和 NIO 提供高效操作I/O 流是 Java 编程中不可或缺的基础组件几乎所有的数据持久化和传输操作都依赖于它。