NIO:通道
使用通道:
1 void channelDemo() { 2 RandomAccessFile aFile = null; 3 ByteBuffer buf = ByteBuffer.allocate(48); 4 FileChannel inChannel = null; 5 try { 6 aFile = new RandomAccessFile("E:\\test\\test.txt", "rw"); 7 inChannel = aFile.getChannel(); 8 int bytesRead = inChannel.read(buf); 9 while (bytesRead != -1) { 10 System.out.print("Read " + bytesRead); 11 //通过flip()方法将Buffer从写模式切换到读模式。 12 buf.flip(); 13 while (buf.hasRemaining()) 14 System.out.print((char) buf.get()); 15 //调用clear()或compact()方法。clear()方法会清空整个缓冲区。 16 // compact()方法只会清除已经读过的数据。任何未读的数据都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。 17 buf.clear(); 18 bytesRead = inChannel.read(buf); 19 } 20 21 } catch (FileNotFoundException e) { 22 e.printStackTrace(); 23 } catch (IOException e) { 24 e.printStackTrace(); 25 } finally { 26 try { 27 aFile.close(); 28 } catch (IOException e) { 29 e.printStackTrace(); 30 } 31 } 32 }