NIO的理解

NIO是同步非阻塞,核心是通道和缓冲区,通道用于传输数据,缓冲区用于存储数据。

1.缓冲区可以保存多个相同类型的数据,例如:

  • ByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • MappedByteBuffer
  • ShortBuffer

2.通道和选择器

Channel和Selector

  • FileChannel: 用于文件的数据读写

  • DatagramChannel: 用于UDP的数据读写

  • SocketChannel: 用于TCP的数据读写,一般是客户端实现

  • ServerSocketChannel: 允许我们监听TCP链接请求,每个请求会创建会一个SocketChannel,一般是服务器实现

文件复制

        RandomAccessFile file1 = new RandomAccessFile("D:\\test.txt","rw");
        FileChannel c1 = file1.getChannel();

        RandomAccessFile file2 = new RandomAccessFile("D:\\tes.txt","rw");
        FileChannel c2 = file2.getChannel();


        long position = 0L;
        c2.transferFrom(c1,position,c1.size());

选择器创建

Selector selector = Selector.open()

3.操作文件的核心Path和Files

Path path = Paths.get("D:\\test.text");
boolean file = Files.exists(path,new LinkOption[]{LinkOption.NOFOLLOW_LINKS});

你可能感兴趣的:(java)