NIO基础知识点整理---selector除外

x33g5p2x  于2021-12-30 转载在 其他  
字(23.4k)|赞(0)|评价(0)|浏览(346)

JVM读取数据模型

程序执行效率更多是由I/O效率决定的

需要等待数据传输

是JVM在I/O方面的效率不足,导致程序效率降低。在操作系统中,可以从硬件上直接读取大块的数据,而JVM的I/O更喜欢小块的数据读取,相当于操作系统视同大卡车运来很多数据,JVM的I/O就喜欢一铲子一铲子的加工这些数据。

在JDK4中引入了NIO,可以最大限度的满足Java程序I/O的需求

  • java.nio包,定义了各种与Buffer相关的类.
  • java.nio.channel包,包含了与Channel和Selector相关的类.
  • java.nio.charset包,与字符集相关的类

在NIO中有三大核心组件:Channel,Buffer,Selector

NIO是什么

传统的IO是面向流的,每次可以从流中读取一个或多个自己,只能向后读取,不能向前移动,NIO是面向缓冲区的,把数据读取到一个缓冲区中,可以在缓冲区中向前/向后移动,增加了程序的灵活性。

在NIO中,所有的数据都需要通过Channel传输,通道可以直接将一块数据映射到内存中,Channel是双向的,不仅可以读取数据。还可以保存数据。程序不能直接读取Channel通道,Channel只与Buffer缓冲区进行交互。

IO流时线程阻塞的,在调用read()/write()读写数据时,线程阻塞,直到数据读取完毕或者数据完全写入,在读写过程中,线程不能做其他的任务。

NIO不是线程阻塞的,当线程从Channel中读取数据时,如果通道中没有可用的数据,线程不阻塞,可用做其他的任务

Buffer

buffer属性

Buffer缓冲区实际上就是一个数组,把数组的内容与信息包装成一个Buffer对象,它提供了一组访问这些信息的方法

缓冲区的重要属性:

1.capacity容量: 指缓冲区可用存储多少个数据,容量在创建Buffer缓冲区时指定大小,创建后不能再修改,如果缓冲区满了,需要清空后才能继续写数据。

2.position表示当前位置,即缓冲区写入/读取的位置,刚刚创建Buffer对象后,position初始化为0,写入一个数据,position就向后面移动一个单元,它的最大值是capacity-1.

当Buffer从写模式切换到读模式,position会被重置为0,从Buffer的开始位置读取数据,每读一个数据,position就向后面移动一个单元.

2.limit上限: 指第一个不能被读出或写入的位置.limit上限后面的单元既不能读也不能写,在Buffer缓冲区的写模式下,limit表示能够写入多少个数据;在读取模式下,limit表示最多可以读取多少个数据。

3.mark标记:设置一个标记位置,可以调用mark方法,把标记设置在position位置,当调用reset()方法时,就把position设置为mark标记的位置。

  1. 0<=mark<=position<=limit<=capacity

Buffer常用API

在NIO中关键的Buffer有:ByteBuffer,CharBuffet,DoubleBuffer,FloatBuffer,IntBufer,LongBuffer,ShortBuffer。

这些Buffer覆盖了能够通过I/O发送的所有基本类型:byte,char,double,flaot.int.long,short等。实际上使用较多的是ByteBuffer和CharBuffer。

  • 每个缓冲区都有一个静态方法allocate(capacity)可以创建一个指定容量的缓冲区;
  • put()方法用于向缓冲区中存储数据;
  • get()方法可以从缓冲区中读取数据;
  • 当缓冲区中还有没有读完的数据,可以调用compact方法进行压缩,将所有未读取的数据复制到Buffer的起始位置,把position设置到最后一个未读元素的后面.limit属性设置为capacity.
  • capacity()方法返回缓冲区的大小
  • hasRemaining()判断当前position后面是否还有可以被处理的数据,即判断position与limit之间是否还有数据可处理。
  • limit()返回limit上限的位置
  • mark()设置缓冲区的标志位置,这个值只能在0–position之间,以后可以通过reset()将position置为mark标记的位置.
  • position()可以返回position当前位置
  • remaining()返回当前position位置与limit之间的数据量
  • reset()方法可以将position设置为mark标记位
  • rewind():将position设置为0,取消mark标志位
  • clear()清空缓冲区,仅仅是修改position标志位0,设置limit为capacity,缓冲区中数据还是存在的
  • flip()方法可以把缓冲区由写模式切换到读取模式,先把limit设置position位置,再把position设置为0;

Buffer的API使用演示

  1. public class BufferAPI
  2. {
  3. public static void main(String[] args) {
  4. //使用字符缓冲区--一个中文字符和英文字符都是一个字符大小,只是所占字节大小不一样
  5. CharBuffer charBuffer=CharBuffer.allocate(12);
  6. curPosition(charBuffer);//position=0,limit=12
  7. //向缓冲区中存储数据
  8. charBuffer.put("大");
  9. charBuffer.put("忽");
  10. charBuffer.put("悠");
  11. curPosition(charBuffer);//position=3,limit=12
  12. //调用flip,把缓冲区从写模式切换为读取模式
  13. charBuffer.flip();
  14. curPosition(charBuffer);//position=0,limit=3
  15. //从缓冲区读取数据
  16. System.out.print(charBuffer.get());
  17. System.out.print(charBuffer.get());
  18. System.out.print(charBuffer.get());
  19. curPosition(charBuffer);//position=3,limit=3
  20. charBuffer.clear();
  21. curPosition(charBuffer);//position=0,limit=12,mark=-1
  22. //往缓冲区中放入数据
  23. charBuffer.put("小");
  24. charBuffer.put("朋");
  25. charBuffer.put("友");
  26. curPosition(charBuffer);//position=3,limit=12
  27. //切换为写模式
  28. charBuffer.flip();//position=0,limit=3,mark=-1
  29. //设置标记
  30. charBuffer.mark();//mark=0
  31. //再读取一个字符
  32. System.out.println(charBuffer.get());
  33. curPosition(charBuffer);//position=1,limit=3
  34. //调用reset()将position重置为mark标记位置
  35. charBuffer.reset();
  36. curPosition(charBuffer);//position=0,limit=3
  37. //调用compact,将没有读取的数据复制到position为0的位置
  38. charBuffer.compact();
  39. curPosition(charBuffer);
  40. //调用clear清空,只是将position=0,limit=capacity,数据依然存在
  41. charBuffer.clear();
  42. curPosition(charBuffer);
  43. //读取数据
  44. System.out.println(charBuffer);
  45. curPosition(charBuffer);
  46. //挨个读取--position与limit之间内容逐个打印
  47. while(charBuffer.hasRemaining())
  48. {
  49. System.out.println(charBuffer.get());
  50. }
  51. curPosition(charBuffer);
  52. }
  53. //打印当前位置的具体信息
  54. public static void curPosition(CharBuffer charBuffer)
  55. {
  56. System.out.println("当前缓冲区容量capacity: "+charBuffer.capacity()
  57. +" 当前缓冲区limit位置: "+charBuffer.limit()+
  58. " 当前缓冲区position指针位置: "+charBuffer.position());
  59. }
  60. }

输出结果:

  1. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 0
  2. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 3
  3. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 3 当前缓冲区position指针位置: 0
  4. 大忽悠当前缓冲区容量capacity: 12 当前缓冲区limit位置: 3 当前缓冲区position指针位置: 3
  5. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 0
  6. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 3
  7. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 3 当前缓冲区position指针位置: 1
  8. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 3 当前缓冲区position指针位置: 0
  9. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 3
  10. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 0
  11. 小朋友
  12. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 0
  13. 当前缓冲区容量capacity: 12 当前缓冲区limit位置: 12 当前缓冲区position指针位置: 12

缓冲区批量数据传输

使用缓冲区就是为了提高数据传输效率,一次读写一个字符或者一个字节效率并不高,可以进行批量的操作,可以借助于数组,把缓冲区中的一块数据读到数组中,也可以把数组中的部分内容保存到缓冲区中

  1. public class BufferAPI
  2. {
  3. public static void main(String[] args) {
  4. //使用字符缓冲区--一个中文字符和英文字符都是一个字符大小,只是所占字节大小不一样
  5. CharBuffer charBuffer=CharBuffer.allocate(12);
  6. //将字符串保存到buffer缓冲区
  7. charBuffer.put("123456654321");
  8. //反转读写模式
  9. charBuffer.flip();//position=0,limit=12
  10. System.out.println(charBuffer);//只会输出position到limit的内容
  11. //通过字符数组,来接收缓冲区里面的数据
  12. char[] dst=new char[8];
  13. //调用get()方法把缓冲区中的数据读到字符数组中
  14. //注意批量传输时大小总是固定的,如果没有指定传输的大小,意味着把数组填满
  15. CharBuffer charBuffer1 = charBuffer.get(dst);
  16. System.out.println(new String(dst));
  17. //get方法返回的缓冲区和最开始定义的是同一个
  18. System.out.println(charBuffer);
  19. System.out.println(charBuffer1);//缓冲区剩余的数据
  20. //继续把buf缓冲区的内容读到字符数组中
  21. //当缓冲区的数据量不足以填满整个数组时,会抛出异常
  22. //charBuffer.get(dst);//BufferUnderflowException
  23. //在批量读取缓冲区数据时,记得查询缓冲区的剩余量
  24. //把小缓冲区的数据填充到大的数组时,要指定缓冲区剩余量的长度
  25. //把buf缓冲区中剩余的数据传输到dst数组的0开始的位置
  26. charBuffer.get(dst,0,charBuffer.remaining());
  27. System.out.println(dst);
  28. //循环读取缓冲区中的数据
  29. charBuffer.clear();
  30. dst=new char[8];
  31. while(charBuffer.hasRemaining())
  32. {
  33. int min = Math.min(dst.length, charBuffer.remaining());
  34. charBuffer.get(dst,0,min);
  35. System.out.println(dst);
  36. }
  37. curPosition(charBuffer);
  38. //向缓冲区存入数据的时候,需要注意缓冲区空间不足的情况,否则会抛出异常
  39. //调整position指针的位置
  40. charBuffer.position(10);
  41. //此时还可以存放两个字符
  42. char[] test={'a','b','c','d'};
  43. charBuffer.put(test,0,charBuffer.remaining());
  44. charBuffer.clear();
  45. System.out.println(charBuffer);
  46. }
  47. //打印当前位置的具体信息
  48. public static void curPosition(CharBuffer charBuffer)
  49. {
  50. System.out.println("capacity: "+charBuffer.capacity()
  51. +" limit: "+charBuffer.limit()+
  52. " position: "+charBuffer.position());
  53. }
  54. }

缓冲区创建的两种方式

1.分配创建缓冲区,allocate()方法分配一个私有的,指定容量大小的数组来存储元素

2.包装操作创建缓冲区,它使用提供的数组作为存储空间来存储缓冲区中的数据,不再分配其他空间

  1. public class BufferAPI
  2. {
  3. public static void main(String[] args) {
  4. //缓冲区创建的两种方式
  5. //1.allocate()
  6. CharBuffer charBuffer1=CharBuffer.allocate(12);
  7. //2.wrap()
  8. CharBuffer charBuffer3=CharBuffer.wrap("大忽悠");
  9. curPosition(charBuffer3);
  10. char[] array=new char[12];
  11. CharBuffer charBuffer2=CharBuffer.wrap(array);
  12. curPosition(charBuffer2);
  13. }
  14. //打印当前位置的具体信息
  15. public static void curPosition(CharBuffer charBuffer)
  16. {
  17. System.out.println("capacity: "+charBuffer.capacity()
  18. +" limit: "+charBuffer.limit()+
  19. " position: "+charBuffer.position());
  20. }
  21. }

调用put方法对向缓冲区中放入数据会直接影响到数组,同样对数组做任何修改也会直接影响到缓冲区对象

  1. char[] array=new char[12];
  2. CharBuffer charBuffer2=CharBuffer.wrap(array);
  3. curPosition(charBuffer2);
  4. charBuffer2.put("嘿嘿嘿");
  5. System.out.println(array);
  6. curPosition(charBuffer2);
  7. array[4]='小';
  8. array[5]='朋';
  9. array[6]='友';
  10. System.out.println(charBuffer2);
  11. curPosition(charBuffer2);

hasArray()方法判断是否有一个可存取的备份数组

如果hasArray()返回true,可以通过array()返回缓冲区对象使用的备份数组的引用

  1. char[] array=new char[12];
  2. CharBuffer charBuffer2=CharBuffer.wrap(array);
  3. charBuffer2.put("嘿嘿嘿");
  4. if(charBuffer2.hasArray())
  5. {
  6. char[] array1 = charBuffer2.array();
  7. System.out.println(array1);
  8. }

缓冲区的复制与分隔

复制操作

  1. public class BufferAPI
  2. {
  3. public static void main(String[] args)
  4. {
  5. CharBuffer charBuffer=CharBuffer.wrap("123456");
  6. //缓冲区的复制
  7. CharBuffer duplicate = charBuffer.duplicate();
  8. System.out.println(duplicate);
  9. //下面可以看出两个缓冲区只用数组是同一个,两个缓冲区对象是不同的对象
  10. //两个缓冲区实际上引用的是同一个数组
  11. duplicate.position(4);
  12. curPosition(duplicate);
  13. curPosition(charBuffer);
  14. }
  15. //打印当前位置的具体信息
  16. public static void curPosition(CharBuffer charBuffer)
  17. {
  18. System.out.println("capacity: "+charBuffer.capacity()
  19. +" limit: "+charBuffer.limit()+
  20. " position: "+charBuffer.position());
  21. }
  22. }

缓冲区的复制,本质是两个不同的缓冲区对象共用一个缓冲数组

分隔操作

分隔缓冲区,slice()方法根据[position.limit)区间创建一个新的缓冲区

  1. public class BufferAPI
  2. {
  3. public static void main(String[] args)
  4. {
  5. CharBuffer charBuffer=CharBuffer.wrap("123456");
  6. charBuffer.position(5);
  7. CharBuffer slice = charBuffer.slice();
  8. curPosition(charBuffer);
  9. curPosition(slice);
  10. }
  11. //打印当前位置的具体信息
  12. public static void curPosition(CharBuffer charBuffer)
  13. {
  14. System.out.println("capacity: "+charBuffer.capacity()
  15. +" limit: "+charBuffer.limit()+
  16. " position: "+charBuffer.position());
  17. }
  18. }

直接字节缓冲区

在硬盘中和操作系统处理的数据都是01二进制,缓冲区中只有ByteBuffer字节缓冲区由资格参与I/O操作。

Channel通道只能使用ByteBuffer作为它的参数。

直接字节缓冲区通常是I/O操作最好的选择,如果使用非直接字节缓冲区可能会导致性能损耗,如果向通道传递一个非直接字节缓冲区,通道可能会先创建一个临时的直接字节缓冲区,将非直接缓冲区的内容复制到这个临时的直接字节缓冲区执行底层的I/O操作。

直接缓冲区时I/O的最佳选择,可能创建直接缓冲区比创建非直接缓冲区的成本要高。直接缓冲区使用的内存是通过调用本地操作系统代码分配的,绕过了JVM的堆栈,现在JVM可能会执行缓冲区的缓存的优化.

ByteBuffer.allocateDirect()方法创建直接字节缓冲区

Channel

Channel是一种新的I/O访问方式,用于在字节缓冲区与通道另一侧的实体(可以是文件也可以是Socket)之间进行传输数据。

Channel可以双向读写数据,也开业实现异步读写。

程序不能直接访问Channel,Channel只能与Buffer缓冲区进行交互,即把通道中的数据读到Buffer缓冲区中,程序从缓冲区中读取数据;

在写操作时,程序把数据写入Buffer缓冲区中,再把缓冲区的数据写入到Channel中.

常用的Channel:

  • FileChannel:读写文件的通道
  • SocketChannel/ServerSocketChannel:读写Socket套接字中的数据
  • DatagramChannel:通过UDP读写网络数据。

注意:

1.通道不能通过构造方法创建

2.通道不能重复使用,一旦创建了一个通道,就表示一个特定的I/O服务建立了一个连接,一旦通道关闭,连接就没了

3.通道可以以默认阻塞的方式运行,也可设置为非阻塞方式运行

Scatter与Gather

Scatte(发散),Gather(聚焦)是通道提供的一个重要功能(有时也成为矢量I/O)

Scatte,Gather是指在多个缓冲区中实现一个简单的I/O操作。

Scatter是指从channel 通道中读取数据,把这些数据按顺序分散写入到多个Buffer缓冲区中

Gather是指在写操作时,将多个Buffer缓冲区的数据写入到同一个Channel中

Scatter,Gather经常用于需要将传输的数据分开处理的场景

如Scatter从一个Channel中读取数据存储到多个Buffer:

  1. //示例伪代码
  2. ByteBuffer c1=ByteBuffer.allocate(3);
  3. ByteBuffer c2=ByteBuffer.allocate(3);
  4. ByteBuffer[] bufArray={buf1,buf2}
  5. Channel.read(bufArray);

Read()方法从Channel中读取数据,按照在数组中的顺序依次存储到缓冲区中。

注意必须在buf1缓冲区满后才能写入buf2缓冲区中。

使用Scatter/Gather处理的数据大小都是固定的

对于不确定数据大小的情况下,不适合用

FileChannel

FileChannel通过RandomAccessFile,FileInputStream,FileOutputStream对象调用getChannel()方法调用。

FileChannel虽然是双向的,既可以读也可以写,但是从FileInputStream流中获得的通道只能读不能写,如果进行写操作会抛出异常;从FileOutputStream流中获得的通道只能写不能读;如果访问的文件时只读的也不能执行写操作。

FileChannel是线程安全的,但是并不是所有的操作都是多线程的,如影响通道位置或者影响文件大小的操作都是单线程的。

1.内存映射文件

FileChannel的map()方法可以把磁盘上的文件整个的映射到计算机的虚拟内存,把这块虚拟内存包装为一个MappedByteBuffer对象,注意: 当前把一个文件映射到虚拟内存中,文件的内容通常不会从硬盘读取到内存。

通过内存映射完成文件的拷贝操作:

  1. public class BufferAPI
  2. {
  3. //当前项目的路径
  4. private static final String project_path=System.getProperty("user.dir")+System.getProperty("file.separator");
  5. //源文件
  6. private final static File src=new File(project_path+"src.txt");
  7. //目的文件
  8. private final static File dst=new File(project_path+"tar.txt");
  9. public static void main(String[] args)
  10. {
  11. //把src.txt以内存映射的方式读取到tar.txt
  12. //使用try-resources写法
  13. try(
  14. FileChannel fin=new FileInputStream(src).getChannel();
  15. FileChannel fout=new FileOutputStream(dst).getChannel();
  16. ) {
  17. //将fin通道里面的数据映射到虚拟内存中
  18. //参数一:映射方式,可读还是可写
  19. //参数二,参数三:从某个位置开始映射,映射多少个字节
  20. MappedByteBuffer mapBuffer = fin.map(FileChannel.MapMode.READ_ONLY, 0, src.length());
  21. //将缓冲区中的数据输出到fout通道中
  22. fout.write(mapBuffer);
  23. //也可以把buffer里面的内容打印出来
  24. mapBuffer.flip();//转换为读模式
  25. //创建字符集
  26. Charset charset = Charset.defaultCharset();
  27. //使用默认字符集将buf里面的字节转换为字符
  28. CharBuffer decode = charset.decode(mapBuffer);
  29. System.out.println("解码后的buffer: "+decode);
  30. } catch (FileNotFoundException e) {
  31. e.printStackTrace();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }

2.FileChannel的双向传输

使用RandomAccessFile获得的通道是双向传输的

将tar.txt文件的内容全部读取出来,然后再次追加到该文件的尾部

  1. public class BufferAPI
  2. {
  3. //当前项目的路径
  4. private static final String project_path=System.getProperty("user.dir")+System.getProperty("file.separator");
  5. public static void main(String[] args)
  6. {
  7. //使用try-resources写法
  8. try(
  9. RandomAccessFile dst=new RandomAccessFile(project_path+"tar.txt","rw");
  10. FileChannel fout=dst.getChannel();
  11. )
  12. {
  13. //把channel中的数据映射到虚拟内存中
  14. MappedByteBuffer mappedByteBuffer = fout.map(FileChannel.MapMode.READ_ONLY, 0, dst.length());
  15. //设置channel的position操作
  16. fout.position(dst.length());
  17. //把缓冲区数据写入到channel中
  18. fout.write(mappedByteBuffer);
  19. } catch (FileNotFoundException e) {
  20. e.printStackTrace();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. }

channel只有position,没有limit和capacity,因为这两个属性是针对缓冲区而言的

3.Filechannel读写文件时,缓冲区固定大小
  1. public class BufferAPI
  2. {
  3. //当前项目的路径
  4. private static final String project_path=System.getProperty("user.dir")+System.getProperty("file.separator");
  5. //源文件
  6. private final static File src=new File(project_path+"src.txt");
  7. //目的文件
  8. private final static File dst=new File(project_path+"dst.txt");
  9. public static void main(String[] args)
  10. {
  11. //使用try-resources写法
  12. try(
  13. FileChannel fin=new FileInputStream(src).getChannel();
  14. FileChannel fout=new FileOutputStream(dst).getChannel();
  15. )
  16. {
  17. //定义固定大小的缓冲区
  18. ByteBuffer byteBuffer=ByteBuffer.allocate(48);
  19. //不断的从通道中读取数据放入缓冲区中
  20. while(fin.read(byteBuffer)!=-1)
  21. {
  22. byteBuffer.flip();//缓冲区从写模式切换为读模式
  23. while(byteBuffer.hasRemaining())
  24. {
  25. //从缓冲中读取数据放入通道中
  26. fout.write(byteBuffer);
  27. }
  28. }
  29. byteBuffer.clear();
  30. } catch (FileNotFoundException e) {
  31. e.printStackTrace();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }

文件不存在,会创建文件

4.通道与通道之间的传输

经常需要把文件从一个位置批量传输到另一个位置,可以直接使用通道到通道之间的传输,不需要中间缓冲区传递数据.

注意,只有FileChannel支持通道到通道之间的传输.

通道到通道的传输非常快速,有的操作系统可以不使用用户空间直接传输数据。

  1. public class BufferAPI
  2. {
  3. //当前项目的路径
  4. private static final String project_path=System.getProperty("user.dir")+System.getProperty("file.separator");
  5. public static void main(String[] args)
  6. {
  7. //使用try-resources写法
  8. try(
  9. RandomAccessFile src= new RandomAccessFile(project_path+"src.txt", "rw");
  10. FileChannel fin=src.getChannel();
  11. FileChannel fout=new FileOutputStream(project_path+"dst.txt").getChannel();
  12. )
  13. {
  14. //transferTo--将当前通道内的数据传输到另一个通道中去
  15. //参数一:从当前通道的哪一个位置进行数据传输
  16. //参数二:传输多少个字节数据
  17. //参数三:目的地的通道
  18. //fin.transferTo(0,src.length(),fout);
  19. //transform
  20. //参数一:源通道
  21. //参数二和三对应上面:从原通道的某个位置,传输多少个字节到现在的通道
  22. fout.transferFrom(fin,0,src.length());
  23. } catch (FileNotFoundException e) {
  24. e.printStackTrace();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }
5.Gather实现

把文件的属性和文件的内容分别存储到不同的缓冲区中,再写入到另外一个文件中

  1. public class BufferAPI
  2. {
  3. //当前项目的路径
  4. private static final String project_path=System.getProperty("user.dir")+System.getProperty("file.separator");
  5. //换行符
  6. private static final String line_separator=System.getProperty("line.separator");
  7. //当前类的.java文件
  8. private static final String curJavaFilePath=project_path+"src\\com\\NIO\\BufferAPI.java";
  9. public static void main(String[] args)
  10. {
  11. File file=new File(curJavaFilePath);
  12. //获取文件绝对路径
  13. String absolutePath = file.getAbsolutePath();
  14. //文件最后一次修改的时间
  15. long lastModified = file.lastModified();
  16. String formatDate = formatDate(lastModified);
  17. //把文件属性存储在缓冲区中
  18. String headerText="file path: "+absolutePath+" "+line_separator
  19. +"file modified: "+formatDate+line_separator;
  20. ByteBuffer headerBuffer=ByteBuffer.wrap(headerText.getBytes());
  21. //存放文件内容类型
  22. ByteBuffer contentBuffer=ByteBuffer.allocate(1024);
  23. //创建一个缓冲区数组
  24. ByteBuffer[] gather={headerBuffer,contentBuffer,null};
  25. String contentType="unkonwn";
  26. Long length=-1l;
  27. //把文件映射到虚拟内存中
  28. try (FileChannel channel = new FileInputStream(file).getChannel();)
  29. {
  30. //把文件映射到虚拟内存中
  31. MappedByteBuffer fileData = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
  32. //把映射到内存上的文件内容保存到gather数组中
  33. gather[2]=fileData;
  34. //文件长度
  35. length=file.length();
  36. //返回当前文件的类型
  37. String name = URLConnection.guessContentTypeFromName(file.getAbsolutePath());
  38. StringBuilder stringBuilder=new StringBuilder();
  39. String string = stringBuilder.append("file Len: " + length+line_separator)
  40. .append("contentType: " + name+line_separator).toString();
  41. gather[1]=contentBuffer.put(string.getBytes());
  42. //反转读写模式
  43. contentBuffer.flip();
  44. //让gather数组里面的内容写入到文件中
  45. FileChannel fileChannel = new FileOutputStream(project_path + "dst.txt").getChannel();
  46. //write返回值如果是0表示写完了,如果不是0则还有数据没写完
  47. while(fileChannel.write(gather)>0)
  48. {}
  49. //写完了,关闭通道
  50. fileChannel.close();
  51. } catch (FileNotFoundException e)
  52. {
  53. addErrorMessageToFile(gather,e.getMessage());
  54. } catch (IOException e) {
  55. addErrorMessageToFile(gather,e.getMessage());
  56. }
  57. }
  58. //如果文件操作出现异常,将出现的异常保存到错误日志中去
  59. public static void addErrorMessageToFile(ByteBuffer[] gather,String error)
  60. {
  61. ByteBuffer wrap = ByteBuffer.wrap(error.getBytes());
  62. gather[2]=wrap;
  63. }
  64. //时间格式化
  65. public static String formatDate(Long epochSecond)
  66. {
  67. Date date=new Date(epochSecond);
  68. DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
  69. String format = dateFormat.format(date);
  70. return format;
  71. }
  72. }

效果:

socketChannel和serverSocketChannel

ServerSocketChannel可以监听新进来的TCP连接通道

SocketChannel是一个连接到TCP网络套接字的通道

服务器端代码—serverSocketChannel实现

  1. public class DHYServerSocketChannel
  2. {
  3. //服务器端的端口号
  4. private static Integer Default_Port=80;
  5. public static void main(String[] args) throws IOException, InterruptedException {
  6. //建立一个未绑定的ServerScoket服务器的通道
  7. java.nio.channels.ServerSocketChannel ssc = java.nio.channels.ServerSocketChannel.open();
  8. //ServerSocketChannel没有bind绑定方法,需要先通过socket()方法获得ServerSocket对象,然后在进行端口号的绑定操作
  9. ssc.socket().bind(new InetSocketAddress(Default_Port));
  10. //设置通道为非阻塞模式,当没有socket没有传入连接时,accept()方法返回null
  11. ssc.configureBlocking(false);
  12. while(true)
  13. {
  14. java.nio.channels.SocketChannel socketChannel = ssc.accept();
  15. //如果没有连接,socketChannel=null
  16. if(socketChannel==null)
  17. {
  18. Thread.sleep(2000);
  19. }
  20. else
  21. {
  22. //有连接传入
  23. //先给客户端发送一个问候
  24. ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
  25. byteBuffer.put("你好,我是服务器".getBytes());
  26. byteBuffer.flip();
  27. socketChannel.write(byteBuffer);
  28. //再读取客户端中发送来的内容
  29. System.out.println("客户端["+socketChannel.socket().getRemoteSocketAddress()+"]");
  30. byteBuffer.clear();
  31. //读取客户端发送的数据,保存到buffer中
  32. socketChannel.read(byteBuffer);
  33. byteBuffer.flip();//切换为读模式
  34. //解码
  35. Charset charset = Charset.defaultCharset();
  36. //解码后生产一个字符缓冲区
  37. CharBuffer decode = charset.decode(byteBuffer);
  38. System.out.println("客户端消息: "+decode);
  39. //关闭服务器与客户端之间的连接
  40. socketChannel.close();
  41. break;
  42. }
  43. }
  44. }
  45. }

客户端端代码—SocketChannel实现

  1. public class DHYSocketChannel
  2. {
  3. //serverSocket的IP地址---即服务器的ip地址
  4. private static String HOST_IP="localhost";
  5. //serverSocket注册的端口号
  6. private static Integer HOST_PORT=80;
  7. public static void main(String[] args) throws IOException {
  8. InetSocketAddress address=new InetSocketAddress(HOST_IP, HOST_PORT);
  9. //创建一个未连接的SocketChannel
  10. SocketChannel socketChannel = SocketChannel.open();
  11. //建立与服务器的连接
  12. socketChannel.connect(address);
  13. //TCP连接需要一定时间,两个连接的建立需要进行包对话
  14. //调用finishConnect()方法完成连接过程,如果没有连接成功返回false
  15. while(!socketChannel.finishConnect())
  16. {
  17. System.out.println("等待连接中...");
  18. }
  19. System.out.println("连接成功");
  20. //向服务器发送消息
  21. ByteBuffer buffer=ByteBuffer.wrap("你好,我是客户端".getBytes());
  22. while(buffer.hasRemaining())
  23. {
  24. socketChannel.write(buffer);
  25. }
  26. //获得服务器发送给客户端的消息
  27. InputStream inputStream = socketChannel.socket().getInputStream();
  28. ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);//channels工具类获得通道
  29. buffer.clear();
  30. readableByteChannel.read(buffer);
  31. buffer.flip();//切换读模式
  32. //解码
  33. Charset charset = Charset.defaultCharset();
  34. CharBuffer decode = charset.decode(buffer);
  35. System.out.println(decode);
  36. }
  37. }

DatagramChannel

DatagramChannel是收发UDP包的通道,与TCP协议不同,UDP发送不进行连接,也不对确认数据是否收到。

  1. ByteBuffer receiveBuffer = ByteBuffer.allocate(64);
  2. receiveBuffer.clear();
  3. SocketAddress receiveAddr = server.receive(receiveBuffer);

SocketAddress可以获得发包的ip、端口等信息,用toString查看,格式如下

/127.0.0.1:57126

连接

udp不存在真正意义上的连接,这里的连接是向特定服务地址用read和write接收发送数据包。

  1. client.connect(new InetSocketAddress("127.0.0.1",10086));
  2. int readSize= client.read(sendBuffer);
  3. server.write(sendBuffer);

read()和write()只有在connect()后才能使用,不然会抛NotYetConnectedException异常。用read()接收时,如果没有接收到包,会抛PortUnreachableException异常。

数据接收端–receiver

  1. public class DHYDatagramReceiver
  2. {
  3. public static void main(String[] args) throws IOException, InterruptedException {
  4. //创建一个未绑定的通道
  5. DatagramChannel datagramChannel=DatagramChannel.open();
  6. //绑定一个端口号
  7. datagramChannel.bind(new InetSocketAddress(80));
  8. //设置为非阻塞
  9. datagramChannel.configureBlocking(false);
  10. //接收键盘数据
  11. Scanner sc=new Scanner(System.in);
  12. ByteBuffer buffer=ByteBuffer.allocate(1024);
  13. //判断是否接受到数据
  14. while(true)
  15. {
  16. //先接收数据
  17. buffer.clear();
  18. //通过receive()接收udp包---从通道中接收数据,放入缓冲区中
  19. InetSocketAddress receive = (InetSocketAddress) datagramChannel.receive(buffer);
  20. //判断是否有接收到数据
  21. if(receive==null)
  22. {
  23. Thread.sleep(2000);
  24. continue;
  25. }
  26. System.out.print("数据来自: "+
  27. receive);
  28. //切换读模式
  29. buffer.flip();
  30. String s = new String(buffer.array(), 0, buffer.limit());
  31. System.out.println(" :"+receive.getPort()+"---->"+s);
  32. //发送数据
  33. String text=sc.nextLine();
  34. //发送的数据,发送给谁
  35. datagramChannel.send(ByteBuffer.wrap(text.getBytes()),receive);
  36. }
  37. }
  38. }

数据发送端—sender

  1. public class DHYDatagramSender
  2. {
  3. public static void main(String[] args) throws IOException {
  4. //创建未绑定的channel
  5. DatagramChannel datagramChannel = DatagramChannel.open();
  6. datagramChannel.configureBlocking(false);
  7. ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
  8. Scanner scanner = new Scanner(System.in);
  9. while(scanner.hasNext())
  10. {
  11. String nextLine = scanner.nextLine();
  12. byteBuffer.clear();
  13. byteBuffer.put(nextLine.getBytes());
  14. byteBuffer.flip();
  15. //发送的数据,发送给谁
  16. datagramChannel.send(byteBuffer,new InetSocketAddress("localhost",80));
  17. //接收数据
  18. byteBuffer.clear();
  19. SocketAddress receive = datagramChannel.receive(byteBuffer);
  20. while (receive==null)
  21. {
  22. receive=datagramChannel.receive(byteBuffer);
  23. }
  24. byteBuffer.flip();
  25. System.out.println(new String(byteBuffer.array(),0,byteBuffer.limit()));
  26. }
  27. }
  28. }

Pipe

pipe管道用于在两个线程之间进行单向的数据连接.

pipe有一个source通道和一个sink通道

创建管道: Pipe pipe=Pipe.open();

向管道中写数据,首先需要访问sink通道

  1. Pipe.SinkChannel sc=pipe.sink();
  2. sc.write(buffer);

读数据需要通过source通道

  1. Pipe.SourceChannel source=pipe.source();
  2. source.read(buffer);

使用演示:

  1. public static void test() throws IOException {
  2. // 1. 获取管道
  3. Pipe pipe = Pipe.open();
  4. // 2. 将缓冲区数据写入到管道
  5. // 2.1 获取一个通道
  6. Pipe.SinkChannel sinkChannel = pipe.sink();
  7. // 2.2 定义缓冲区
  8. ByteBuffer buffer = ByteBuffer.allocate(48);
  9. buffer.put("发送数据".getBytes());
  10. buffer.flip(); // 切换数据模式
  11. // 2.3 将数据写入到管道
  12. sinkChannel.write(buffer);
  13. // 3. 从管道读取数据
  14. Pipe.SourceChannel sourceChannel = pipe.source();
  15. buffer.flip();
  16. int len = sourceChannel.read(buffer);
  17. System.out.println(new String(buffer.array(), 0, len));
  18. // 4. 关闭管道
  19. sinkChannel.close();
  20. sourceChannel.close();
  21. }

演示在两个线程之间使用pipe管道进行数据的传输:

使用PipedOutPutStream和PipedInputStream两个类分别是管道输出流和管道输入流类

在管道通信时,线程A向PipedOutPutStream中写入数据,这些数据会自动发送到对应的PipedInputStream中

线程B可以从PipedInputStream中读取数据

  1. public class DHYPipe
  2. {
  3. public static void main(String[] args) throws IOException {
  4. //创建输入流管道
  5. PipedInputStream in=new PipedInputStream();
  6. //创建输出流管道
  7. PipedOutputStream out=new PipedOutputStream();
  8. //在输入流管道和输出流管道之间建立连接
  9. in.connect(out);
  10. //或者
  11. //out.connect(in);
  12. //创建线程
  13. new Thread(new Sender(out)).start();
  14. new Thread(new Receiver(in)).start();
  15. }
  16. }
  17. //发送端
  18. class Sender implements Runnable{
  19. PipedOutputStream out;
  20. public Sender(PipedOutputStream out) {
  21. this.out = out;
  22. }
  23. @Override
  24. public void run() {
  25. //模拟发送数据
  26. try
  27. {
  28. for(int i=0;i<10;i++) {
  29. out.write(("你好第" + i + "个大忽悠\n").getBytes(StandardCharsets.UTF_8));
  30. }
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }finally {
  34. try {
  35. out.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  41. }
  42. //接收端
  43. class Receiver implements Runnable
  44. {
  45. PipedInputStream in;
  46. public Receiver(PipedInputStream in) {
  47. this.in = in;
  48. }
  49. @Override
  50. public void run() {
  51. //接收数据
  52. byte[] bytes=new byte[1024];
  53. try {
  54. int len;
  55. while((len=in.read(bytes))!=-1)
  56. {
  57. System.out.println(new String(bytes,0,len));
  58. }
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. finally {
  63. try {
  64. in.close();
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70. }

使用sinkChannel和sourceChannel完成演示

  1. public class DHYPipe
  2. {
  3. public static void main(String[] args) throws IOException {
  4. //获取管道
  5. Pipe pipe=Pipe.open();
  6. //创建线程
  7. new Thread(new Sender(pipe.sink())).start();
  8. new Thread(new Receiver(pipe.source())).start();
  9. }
  10. }
  11. //发送端
  12. class Sender implements Runnable{
  13. Pipe.SinkChannel sinkChannel;
  14. public Sender(Pipe.SinkChannel sinkChannel) throws IOException {
  15. this.sinkChannel = sinkChannel;
  16. //设置为非阻塞
  17. sinkChannel.configureBlocking(false);
  18. }
  19. @Override
  20. public void run() {
  21. //模拟发送数据
  22. try
  23. {
  24. sinkChannel.write(ByteBuffer.wrap("我是大忽悠".getBytes()));
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }finally {
  28. try {
  29. sinkChannel.close();
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. }
  35. }
  36. //接收端
  37. class Receiver implements Runnable
  38. {
  39. Pipe.SourceChannel sourceChannel;
  40. public Receiver(Pipe.SourceChannel sourceChannel) {
  41. this.sourceChannel = sourceChannel;
  42. }
  43. @Override
  44. public void run() {
  45. try {
  46. ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
  47. sourceChannel.read(byteBuffer);
  48. byteBuffer.flip();
  49. Charset charset = Charset.defaultCharset();
  50. CharBuffer decode = charset.decode(byteBuffer);
  51. System.out.println(decode);
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. finally {
  56. try {
  57. sourceChannel.close();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. }
  63. }

补充知识点整理

HTTP,状态码,TCP、UDP等网络协议

图解HTTP,状态码,TCP、UDP等网络协议相关总结(持续更新)

UrlConnection

URLConnection

Channels

Channels

相关文章