缓冲区Buffer与通道Channel

一、一般来说缓冲区和通道结合在一起使用,写入文件的时候,需要先存放在缓冲区,然后通过通道写入。读取文件的时候也类似,通过通道读取在缓冲区。然后通过缓冲区获取文件内容。

     Buffer针对每一种java基本类型都有实现。Channel针对不同的使用对象也有不同的实现,一般常见的为FileChannel与SocketChannel两类。

    Buffer底层实现为数组,有三个重要的参数,position,limit,capacity,分别代表当前位置,剩余空间,最大容量

    Buffer有两种模式,读模式与写模式。通过方法flip()进入读取模式,clear()方法进入写入模式。

 

二、代码实例:

package nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO拷贝文件(Buffer与FileChannel的使用实例)
 * 
 * @author 
 * @version $Id: CopyFile.java, v 0.1 2014年3月2日 下午12:34:55  Exp $
 */
public class CopyFile {

    public static void main(String[] args) throws Exception {

        String srcFile = "D://1.wmv";
        String targetFile = "D://2.wmv";

        FileInputStream fin = null;
        FileOutputStream fout = null;
        FileChannel finc = null;
        FileChannel foutc = null;

        try {
            fin = new FileInputStream(srcFile);
            fout = new FileOutputStream(targetFile);
            finc = fin.getChannel();
            foutc = fout.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            while (true) {
                buffer.clear();
                int n = finc.read(buffer);
                if (n == -1) {
                    break;
                }

                buffer.flip();
                foutc.write(buffer);
            }

        } catch (Exception e) {
            e.fillInStackTrace();
        } finally {
            if (finc != null) {
                finc.close();
            }
            if (foutc != null) {
                foutc.close();
            }
            if (fin != null) {
                fin.close();
            }
            if (fout != null) {
                fout.close();
            }
        }
    }
}

 

  上面的代码中,通过通道将文件内容读取到缓冲区,然后通过通道写入到文件。Buffer在文件读取之前调用clear,在文件写入之前调用flip。

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章