java io中的几个要点

1 设计模式

java io的设计分为字符流(Reader,Writer)和字节流(InputStream,OutputStream),其中包含两个设计模式

1 Adapter(适配器)

    stream -> reader

   

  InputStreamReader ir = new InputStreamReader(System.in);

  

2 Decorator(装饰器)

    stream -> 增加了功能的stream

 

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("res/input.data"));  

  

2 缓冲区

普通写文件  

FileOutputStream fos = new FileOutputStream(new File("c:/data.txt"));
        for (int i = 0; i < 100; i++) {
            fos.write(i);
        }
        fos.close();

由于没有缓冲区,每次执行fos.wirte(i),程序就直接向文件中写入i,而每次写文件势必调用操作系统API,从而导致效率低下

缓冲区写文件

    FileOutputStream fos = new FileOutputStream(new File("c:/data.txt"));
        //加入缓冲机制
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        for (int i = 0; i < 100; i++) {
            bos.write(i);
        }
        //确保缓冲区内容全部写入文件
        bos.flush();
        bos.close();

加入缓冲区机制后,执行fos.write(i)时,程序会把i放入缓冲区中,当缓冲区满时才把缓冲区的内容一起写入文件,从而提高了效率

而f调用flush是保证清空缓存

 

3 新I/O

java.nio.*包引入了新的Java I/O 类库,目的在于提高速度.其速度的提高来自于所用的数据结构更接近于I/O的方式:通道和缓冲器.

通道要么从缓冲器写数据,要么从缓冲器读数据,所以缓冲器是数据的载体.

简单代码:

//得到通道
        FileChannel fc = new RandomAccessFile("C:/data.txt", "rw").getChannel();
        //往缓冲器写数据
        fc.write(ByteBuffer.wrap("data".getBytes()));
        fc.close();

 

posted @ 2012-05-18 20:06  _SharpCode  阅读(182)  评论(0编辑  收藏  举报