java8中nio通道(Channel)的原理与获取

2025-10-13 23:42:01

1、通道:用于源节点与目标节点的连接,在java nio中负责缓冲区中数据的传输。Channel本身不存储数据,因此需要配合缓冲区进行传输。

java8中nio通道(Channel)的原理与获取

2、通道的主要实现类

java.nio.Channels.Channel接口:

     --FileChannel

     --SocketChannel

     --ServerSocketChannel

     --DatagramChannel

java8中nio通道(Channel)的原理与获取

3、FileChannel通过open()方法得到通道:

FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), 

                StandardOpenOption.READ);

        FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"),

                StandardOpenOption.WRITE,

                StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);

java8中nio通道(Channel)的原理与获取

4、获取通道的三种方式:

1、java针对支持通道的类提供了getChannel()方法

     本地IO:

      FileInputStream/FileOutputStream

      RandomAccessFile

     网络IO:

    Socket

    ServerSocket

    DatagramSocket

@Test

    public void test1() throws Exception{

        FileInputStream fis = new FileInputStream("1.jpg");

        FileOutputStream fos = new FileOutputStream("2.jpg");

        FileChannel inChannel = fis.getChannel();

        FileChannel outChannel = fos.getChannel();

    }

java8中nio通道(Channel)的原理与获取

5、在JDK1.7中的NIO.2针对各个通道提供了静态方法open()

//使用直接缓冲区完成文件的复制(内存映射文件)

    @Test

    public void test2() throws Exception{

        FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);

        FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);

        

    }

java8中nio通道(Channel)的原理与获取

6、在JDK1.7中NIO.2的Files工具类的newByteChannels

@Test

    public void test3() throws Exception{

        ByteChannel byteChannel = Files.newByteChannel(Paths.get("1.jpg"),

                StandardOpenOption.READ);

    }

java8中nio通道(Channel)的原理与获取

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢