Java NIO知识整理

来源:互联网 发布:贝塔无敌软件 编辑:程序博客网 时间:2024/05/21 08:04

前几天学了下NIO这块,因之前基本没用到过也算是新知识,这篇文章着重分享Channel,内存映射,缓冲区不会做过多介绍,有兴趣可以百度一下找资料看

一   使用通道边读边写的经典写法

以复制图片到同一个目录为例,把wp.jpg复制一份放到d盘下

package com.debug;import java.io.*;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class UseChanel01 {public static void main(String[] args) throws Exception {        File f1=new File("d:"+File.separator+"wp.jpg");        File f2=new File("d:"+File.separator+"wp01.jpg");        FileInputStream in=new FileInputStream(f1);        FileOutputStream out=new FileOutputStream(f2);                //取得输入输出流的通道        FileChannel inChanel=in.getChannel();        FileChannel outChanel=out.getChannel();        //开辟缓冲        ByteBuffer buf=ByteBuffer.allocate(1024);                while(inChanel.read(buf)!=-1) {        buf.flip();//重设缓冲区        outChanel.write(buf);//输出到缓冲区        buf.clear();//清空缓冲区                }        outChanel.close();        inChanel.close();        out.close();        in.close();                }}

二  NIO2的写法

NIO2之后简化了获取Channel的方法,不需要通过InputStream和OutoutStream获取,代码如下

package com.debug;import java.io.File;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;import java.nio.file.Paths;import java.nio.file.StandardOpenOption;public class UseChannel02 {public static void main(String[] args) throws Exception {//NIO2 取得channel(不需要通过输入输出流取得)FileChannel inChaeenl=FileChannel.open(Paths.get("d:",File.separator,"wp.jpg"), StandardOpenOption.READ);FileChannel outChaeenl=FileChannel.open(Paths.get("d:",File.separator,"wp03.jpg"),StandardOpenOption.READ, StandardOpenOption.WRITE,StandardOpenOption.CREATE);//使用内存映射的方式'边读边写'MappedByteBuffer mapByteInBuffer=inChaeenl.map(MapMode.READ_ONLY, 0, inChaeenl.size());MappedByteBuffer  mapByteOutBuffer=outChaeenl.map(MapMode.READ_WRITE, 0, inChaeenl.size());byte[] dst=new byte[mapByteInBuffer.limit()];mapByteInBuffer.get(dst);mapByteOutBuffer.put(dst);outChaeenl.close();inChaeenl.close();}}

三  除使用内存映射的方式还有其他使用起来更简洁的API

package com.debug;import java.io.File;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;import java.nio.file.Paths;import java.nio.file.StandardOpenOption;public class UseChannel03 {public static void main(String[] args) throws Exception {//NIO2 取得channelFileChannel inChaeenl=FileChannel.open(Paths.get("d:",File.separator,"wp.jpg"), StandardOpenOption.READ);FileChannel outChaeenl=FileChannel.open(Paths.get("d:",File.separator,"wp04.jpg"),StandardOpenOption.READ, StandardOpenOption.WRITE,StandardOpenOption.CREATE);//使用transferFrom或者transferTo进行边读边写(最简洁的方式)outChaeenl.transferFrom(inChaeenl, 0, inChaeenl.size());outChaeenl.close();inChaeenl.close();}}


原创粉丝点击