java学习笔记 IO学习笔记2 IO流-字节流

来源:互联网 发布:板金放样展开图软件 编辑:程序博客网 时间:2024/06/07 23:37

IO流从功能上可以分为:输入流和输出流。

从结构上可以分为:1)字节流:使用接口InputStream和OutputStream

                                    2)字符流:使用接口Reader和Writer 。 字符流,底层也是字节流来是实现。


读数据流的逻辑:open a stream ->while more information -> read information ->close information

写数据流的逻辑:open a stream ->while more information -> write information ->close information

一般输入输出的写法:

import java.io.File;import java.io.FileInputStream;import java.io.InputStream;public class IOStreamTest {public static void main(String[] args) throws Exception {InputStream is = new FileInputStream(new File("c:" +File.separator+"Test.txt"));byte[] buffer = new byte[2048];int length = 0;// 当读出的数据长度为-1时候,表示数据已经读完了while(-1!=(length= is.read(buffer, 0, buffer.length))){String str = new String(buffer,0,length);// 打印出每一行数据System.out.print(str);}        // 关闭输入流is.close();}}
输出文件:

                OutputStream os = new FileOutputStream(new File("hello.txt"));String str = "this is hello world!!";byte[] buffer1 = str.getBytes();os.write(buffer1);os.close();

字节流内分为 节点流和过滤流

节点流:是从特定的地方读取写入的流类,都直接实现了inputStream 和 outputStream

过滤流:是使用节点流作为输入输出的流类。常用的是以FilterInputStream和FilterOutputStram为父类的。而两者也是继承自inputStream 和 outputStream

也就是说过滤流无法直接与输入输出打交道,他只能通过包装节点流,对输入输出进行相关操作。

输入---节点流---过滤流--过滤流--节点流-输出

这里就用到java中的另外一种设计模式。装饰模式(Decorator)将在下一篇介绍,可以通过动态的方式扩展对象的功能。

例如:

               // 用BufferedOutputStream包转节点流FileOutputStreamBufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("hello world.txt"));bos.write("hello world!!".getBytes());bos.write("123456789!".getBytes());// 流关闭前,数据不会写入文件中bos.close();


0 0
原创粉丝点击