Java程序设计及应用 李宗军 07 2新.ppt
文本预览下载声明
第14讲:I/O编程(2) 内容提要 流模型 字节流 低级流 高级流 字符流 低级流 高级流 NIO简介 流模型 Java 中数据流这个模型类似于管道中的水流 : 低级字节流 低级流都与外部设备(如磁盘文件)相连,就像深井中的水龙带一样,里面的数据流量不可能太大,Java设计低级流的流量为每读/写一次一个字节(byte),即低级流是以字节为单位来传输的。 最常用的低级字节流莫过于: FileInputStream FileOutputStream 把这两个类研究透了,其他的低级流都是类似的,读者查阅相应的JDK API即可。 FileInputStream 构造方法有: FileInputStream(File file) throws FileNotFoundException FileInputStream(String name) throws FileNotFoundException 读取数据用到read()方法: int read() throws IOException int read(byte[] b) throws IOException int read(byte[] b, int off, int len) throws IOException 例程 FileOutputStream FileOutputStream与FileInputStream是一对,前者是输出流,而后者是输入流,其道理是一样的,下面列出其构造: FileOutputStream(File file) FileOutputStream(File file, boolean append) FileOutputStream(String name) FileOutputStream(String name, boolean append) 下面列出其操作方法: void write(byte[] b) void write(byte[] b, int off, int len) void write(int b) 常用的其他低级流 InputStream OutputStream ByteArrayInputStream ByteArrayOutputStream PipedInputStream PipedOutputStream 高级字节流 若与外部设备以字节为单位进行数据交换,使用低级流就足够了,但很多时候交换的数据单位不能是字节,例如int、double、String等类型的数据以及汉字等,这时就需要高级流了。 高级流不直接与外部设备连接,而是与低级流或其他高级流衔接,用于对流经的数据进行特别处理(如过滤、整理等)。典型的高级流主要有DataOutputStream和DataInputStream。 DataOutputStream 构造方法: DataOutputStream(OutputStreamout) 功能方法 void write(int b) void write(byte[] b, int off, int len) void writeBoolean(boolean v) void writeByte(int v) void writeChar(int v) void writeShort(int v) void writeInt(int v) void writeLong(long v) void writeFloat(float v) void writeDouble(double v) void writeUTF(String str) 例程 DataInputStream DataInputStream类似DataOutputStream,读者可查阅JDK API,不再赘述。 例程 其他常用字节高级流 高级流通常都继承自类FilterOutputStream,常用的高级流还有: BufferedInputStream BufferedOutputStream PrintStream PushbackInputStream 字符流 字符流是以Reader、Writer为根类的两个独立的类继承体系,类似字节流,区别在于字符流用于处理字符(即文本,注意Java字符采用Unicode双字节表示),涉及在JVM内部(采用UTF-16编码)和外部(采用操作系统默认的字符集编码)进行字符编码的转换。而字节流用于处理字节,不涉及字符编码。 字符流也有低级和高级之别,低级字符流与外部设备直接连接,高级字符流不能与外部设备直接连接,而是与低级字符流或其他高级字符流连接。 低级的字符流中比较典型的要数FileWriter和
显示全部