NIO快读写

NIO是块I/O,区别于原来的的流I/O,从java1.4开始加入,有更高的效率。
NIO的输入输出加入通道的概念,用通道连接文件进行I/O,通道另一头连接到一个缓冲区(如java.nio.Buffer)。
如我们可以从FileInputStream获取一个通道fcin,然后从通道读取数据到缓冲区buff:fcin.read(buff),这样数据就从文件进入缓冲区。
以下例子:
读取一个文件,写入另一个文件

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class CopyFile {
    static public void main(String args[]) throws Exception {
        String file_in = "e:/mnt/in";
        String file_out = "e:/mnt/out";

        FileInputStream fin = new FileInputStream(file_in);
        FileOutputStream fout = new FileOutputStream(file_out);

        FileChannel fcin = fin.getChannel();
        FileChannel fcout = fout.getChannel();

        ByteBuffer byteBuf = ByteBuffer.allocate(1024);

        while (true) {
            byteBuf.clear();
            if (fcin.read(byteBuf) == -1)
                break;
            byteBuf.flip();
            fcout.write(byteBuf);
        }
    }
}

缓冲区的操作:
除了从通道读数据到缓冲区,或者将缓冲区数据写入通道。还可以对缓冲区进行直接读写,用put和get函数。

猜你喜欢

转载自blog.csdn.net/xuejianbest/article/details/84822098
NIO
今日推荐