ByteBuffer

jdk在数组的操作上提供的API很少,所以在NIO之前我们只能自己对byte[]进行一些简单处理和封装,非常麻烦。NIO提供了一系列的Buffer类,尤其是ByteBuffer进行数据处理是非常方便的,Buffer有几个属性:

  1. capacity:buffer的容量。
  2. limit:读写操作的最大索引。
  3. position:当前读写的索引。
  4. mark:用于标记某个position,当调用reset方法使得position=mark。

Channel

和IO的InputStream和OutputStream,但Channel是双向的。并和Buffer结合使用。常用的Channel:
FileChannel
DatagramChannel
SocketChannel
ServerSocketChannel
下面是文件Channel的使用方式:

  1. private static void useNio(){
  2. RandomAccessFile aFile = null;
  3. try {
  4. aFile = new RandomAccessFile("/Users/sschen/Documents/SerialVersion.txt", "rw");
  5. FileChannel inChannel = aFile.getChannel();
  6. ByteBuffer byteBuffer = ByteBuffer.allocate(48);
  7. int byteReader = inChannel.read(byteBuffer);
  8. while (byteReader != -1) {
  9. System.out.println("Read:" + byteReader);
  10. byteBuffer.flip();
  11. while (byteBuffer.hasRemaining()) {
  12. System.out.println((char)byteBuffer.get());
  13. }
  14. byteBuffer.clear();
  15. byteReader = inChannel.read(byteBuffer);
  16. }
  17. } catch (FileNotFoundException e) {
  18. e.printStackTrace();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. finally {
  23. try {
  24. aFile.close();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }

Selector

通过Selector,一个线程可以管理多个Channel,也就是多个Socket。