package nio;

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

//测试channel
//使用基于流的channel方式
public class testChannel {
    public static void main(String[] a){
        //传统方式的channel方式
        try {
            FileInputStream fileInputStream = new FileInputStream("e:/11.txt");//获取输入流
            FileChannel fileChannel = fileInputStream.getChannel();//获取channel

            FileOutputStream fileOutputStream = new FileOutputStream("e:/22.txt");//获取输出流
            FileChannel fileChannel1 = fileOutputStream.getChannel();

            //创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //从通道中读取数据
            while (fileChannel.read(byteBuffer) != -1)
            {
                //转换为读数据模式
                byteBuffer.flip();
                fileChannel1.write(byteBuffer);
                //清空缓冲区
                byteBuffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

记得要关闭流!本例没有关闭。

基于内存映射文件方式的文件读写

package nio;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

//使用内存映射文件的方式
//加速输入输出流的传递
//使用1.7以后的新的创建管道的方式
public class testMapChannel {
    public static void main(String[] a){
        try {
            //获取文件的channel,并且以读的模式
            FileChannel fileChannel = FileChannel.open(Paths.get("e:/11.txt"), StandardOpenOption.READ);
            //获取文件的channel,以写的模式
            FileChannel fileChannel1 = FileChannel.open(Paths.get("e://33.txt"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);

            //使用内存映射文件的方式,基于channel的传输完成文件的读写操作
            fileChannel.transferTo(0,fileChannel.size(),fileChannel1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

基于内存映射文件的方式,文件的读写完全由os来操作,因此会存在不稳定性,应在特定的场合选择使用

 

10-07 13:43