javaio技术
第 6章 Java IO 技术
6. Java IO 技术
在本章,我们将一起学习:
n Java IO 技术概述
n 常用 IO 流的使用
n NIO
n 利用 Java 进行常用文档的读写
6.1 I/O 技术概述
计算机中的数据可能来自键盘输入、可能来自网络、可能来自外存中的文件、可能来自内
存……,数据可能发送到屏幕显示、可能发送到网络、可能发送到外存中的文件,可能发送到打
印机……。在数据的传输过程中,涉及到数据的存储、转换、处理等。
在 Java 中,数据的输入和输出都是以流 (Stream)的方式来处理。Stream 是任何有能
力产出数据的数据源,或是任何有能力接收数据的接收源。
JDK 中与输入输出相关的包和类都集中存放在 java.io 包中。其中包含 5 个重要的类:
InputStream、OutputStream、Reader、Writer 和 File。 几乎所有与 I/O 相关的类
都继承了这 5 个类。利用这些类提供的方法,Java 可以方便地实现多种 I/O 操作和复杂的文
件和目录管理。
Java 中 的流 按单 位 可 分 为字 节 流 和字 符 流 。按 Java 的命 名 惯 例 ,凡 是 以
InputStream/OutputStream 结尾的类均为字节流,凡是以 Reader/Writer 结尾的类均
为 Unicode 字符流。
按流的方向 (以程序为参照物)可分为输入流和输出流。 输入流是从键盘、磁盘文件或网
络等流向程序的数据流。输出流是从程序流向显示器、打印机、磁盘文件、网络的数据流。
图 61 输入流和输出流示意
Java 中最基本的流是字节流。Java 通过 InputStream 类和 OutputStream 类及其子
类来提供了方便的字节流的读写方法。为了方便处理双字节的 Unicode 字符,Java 通过
Reader、Writer 类及其子类,提供了字节流和字符流的相互转换、字符流的读写等方法。
在 JDK1.1 之前,只有普通的字节流。为提高运行效率和方便数据处理,从 JDK1.1 开始,
提供了专门处理 Unicode 字符流的 Reader 和 Writer 类 ;提供了读写效率更高的带缓冲区
的 BufferedReader、BufferedWriter 等类;提供了以字节流为基础的用于对象状态的永
久化保存机制;从 JDK1.4 开始,Java 开始提供新的 I/O 处理类库-NIO。
6.1.1 InputStream 类和 OutputStream 类
以字节为导向的数据流,表示以字节(Byte)为单位从 stream 中读取或往 stream 中写
入字节数据。在学习中要注意,输入和输出只是方向不同,类中的方法几乎是一一对应的。
1.InputStream 类
public abstract class InputStream extends Object implements Closeable
InputStream 字节流的常用子类主要包括:
l ByteArrayInputStream:包含一个内部缓冲区,该缓冲区包含从流中读取的字节。
第 131 页
张延军编著
第 6章 Java IO 技术
l FileInputStream :负责从文件系统中的某个文件中获得输入字节。
l FilterInputStream:包含其他一些输入流,它将这些流用作其基本数据源,它可
以直接传输数据或提供一些额外的功能。
l DataInputStream :负责八种基本数据类型的输入
l ObjectInputStream:对以前使用 ObjectOutputStream 写入的基本数据和对
象进行反序列化。
l PipedInputStream:线程通信,管