NIO的两种基本实现方式
1. 利用通道完成文件的复制(非直接缓冲区)
@Test public void test1(){ FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; try { fis = new FileInputStream("1.jpg"); fos = new FileOutputStream("2.jpg"); //获取通道 inChannel = fis.getChannel(); outChannel = fos.getChannel(); //分配制定大小的缓冲区 ByteBuffer buf = ByteBuffer.allocate(1024); //将通道中的数据存入缓冲区中 while (inChannel.read(buf) != -1){ //切换为读取数据的模式 buf.flip(); //将缓冲区中的数据写入通道 outChannel.write(buf); buf.clear(); } } catch (IOException e) { e.printStackTrace(); } finally { if (outChannel != null){ try { outChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if (inChannel != null){ try { inChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2. 使用直接缓冲区完成文件的复制(内存映射文件)
@Test public void test2() throws IOException{ FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW); //内存映射文件 MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size()); //直接对缓冲区进行数据的读写操作 byte[] dst = new byte[inMappedBuf.limit()]; inMappedBuf.get(dst); outMappedBuf.put(dst); inChannel.close(); outChannel.close(); }
3. 通道之间的数据传输(底层自动创建缓冲区)
@Test public void test3() throws IOException{ FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("4.jpg"),StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW); //inChannel.transferTo(0,inChannel.size(),outChannel); outChannel.transferFrom(inChannel,0,inChannel.size()); inChannel.close(); outChannel.close(); }

浙公网安备 33010602011771号