一、通道(Channel): 用于源节点与目标节点的连接。在java NIO中负责缓冲区中数据的传输。Channel本身不存储数据,因此需要配合缓冲区进行传输。
二、通道的主要实现类
java.nio.channels.Channel接口:
|– FileChannel
|– SocketChannel
|– ServerSocketChannel
|– DatagramChannel
三、获取通道
1、java针对支持通道的类提供了getChannel()方法
本地IO:
FileInputStream/FileOutputStream
RandomAccessFile
网络IO:
Socket
ServerSocket
DatagramSocket
2、在jdk1.7中NIO.2针对各个通道提供了静态方法open()
3、在jdk1.7中NIO.2的Files工具类的newByteChannel()
1 @Test //利用通道完成文件复制 2 public void test4() throws FileNotFoundException{ 3 FileInputStream fis = new FileInputStream("1.mp4"); 4 FileOutputStream fos=new FileOutputStream("2.mp4"); 5 //1、获取通道 6 FileChannel inChannel = fis.getChannel(); 7 FileChannel outChannel = fos.getChannel(); 8 try { 9 //2、分配一个指定大小的缓冲区 10 ByteBuffer buf=ByteBuffer.allocate(1024); 11 //3、将通道中的数据存入缓冲区 12 while(inChannel.read(buf)!=-1){ 13 //4、将缓冲区中的数据写入通道中 14 buf.flip(); //切换读取数据模式 15 outChannel.write(buf); 16 buf.clear(); 17 } 18 } catch (FileNotFoundException e) { 19 e.printStackTrace(); 20 } catch (IOException e) { 21 e.printStackTrace(); 22 }finally{ 23 try { 24 outChannel.close(); 25 } catch (Exception e) { 26 e.printStackTrace(); 27 } 28 try { 29 inChannel.close(); 30 } catch (IOException e) { 31 e.printStackTrace(); 32 } 33 try { 34 fos.close(); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 try { 39 fis.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 } 44 } 45 46 47 @Test //使用直接缓冲区完成文件的复制 48 public void test5() throws IOException{ 49 FileChannel inChannel=FileChannel.open(Paths.get("1.mp4"),StandardOpenOption.READ); 50 FileChannel outChannel=FileChannel.open(Paths.get("2.mp4"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW); 51 //内存映射文件 52 MappedByteBuffer inMappedBuf=inChannel.map(MapMode.READ_ONLY,0,inChannel.size()); 53 MappedByteBuffer outMappedBuf=outChannel.map(MapMode.READ_WRITE,0,inChannel.size()); 54 //直接对缓冲区进行数据的读写操作 55 byte[] dst=new byte[inMappedBuf.limit()]; 56 inMappedBuf.get(dst); 57 outMappedBuf.put(dst); 58 outChannel.close(); 59 inChannel.close(); 60 }
四、通道之间的数据传输
1 @Test // 通道之间的数据传输(直接缓冲区) 2 public void test6() throws IOException{ 3 FileChannel inChannel=FileChannel.open(Paths.get("1.mp4"),StandardOpenOption.READ); 4 FileChannel outChannel=FileChannel.open(Paths.get("2.mp4"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE); 5 //inChannel.transferTo(0,inChannel.size(),outChannel); //二选一即可 6 outChannel.transferFrom(inChannel,0,inChannel.size()); 7 outChannel.close(); 8 inChannel.close(); 9 }