NIO简述
Java NIO ( New IO )是从 Java 1.4 版本开始引入的一个新的 IO API ,
可以替代标准的 Java IO API 。NIO 与原来的 IO 有同样的作用和目的,但是使用的方式完全不同, NIO 支持面向缓冲区的、基于通道的 IO 操作。 NIO 将以更加高效的方式进行文件的读写操作.
NIO与IO的区别
NIO IO
面向缓冲区(BufferOriented) 面向流(StreamOriented)
非阻塞IO(NonBlockingIO) 阻塞IO(BlockingIO)
选择器(Selectors) 无
通道(Channel)与缓冲区(Buffer)
Java NIO 系统的核心在于:通道 (Channel) 和缓冲区(Buffer) 。
通道表示打开到 IO 设备 ( 例如:文件、套接字 ) 的连接。若需要使用 NIO 系统,需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。
简而言之, Channel 负责传输, Buffer 负责存储
NIO复制文件
这里我提供了四种复制文件的方法,并且给出了这四种方法的运行效率(时长),文件是一个12.2M的歌曲文件
方式一,创建通道和缓冲区
耗时1848毫秒
FileInputStream in = new FileInputStream("歌曲串烧.mp3");
FileOutputStream out = new FileOutputStream("歌曲串烧2.mp3");
FileChannel inch = in.getChannel();
FileChannel outch = out.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while((inch.read(byteBuffer))!=-1){
//切换读取模式
byteBuffer.flip();
outch.write(byteBuffer);
byteBuffer.clear();
}
inch.close();
outch.close();
in.close();
out.close();
方式二,利用FileChannel中的静态方法
耗时1050毫秒
FileChannel inch = FileChannel.open(Paths.get("歌曲串烧.mp3"), StandardOpenOption.READ);
FileChannel outch = FileChannel.open(Paths.get("歌曲串烧2.mp3"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while((inch.read(byteBuffer))!=-1){
//切换读取模式
byteBuffer.flip();
outch.write(byteBuffer);
byteBuffer.clear();
}
inch.close();
outch.close();
方式三,采用直接缓冲区,来复制文件
耗时287毫秒
FileChannel inch = FileChannel.open(Paths.get("歌曲串烧.mp3"), StandardOpenOption.READ);
FileChannel outch = FileChannel.open(Paths.get("歌曲串烧2.mp3"), StandardOpenOption.READ,StandardOpenOption.WRITE, StandardOpenOption.CREATE);
MappedByteBuffer inmap = inch.map(FileChannel.MapMode.READ_ONLY, 0, inch.size());
MappedByteBuffer outmap = outch.map(FileChannel.MapMode.READ_WRITE, 0, inch.size());
byte[] bytes = new byte[inmap.limit()];
inmap.get(bytes);
outmap.put(bytes);
inch.close();
outch.close();
方式四,Files工具类下的copy方法
耗时109毫秒
Files.copy(Paths.get("歌曲串烧.mp3"),Paths.get("歌曲串烧2.mp3"), StandardCopyOption.REPLACE_EXISTING);
总结
这四种方法中,Files工具类下的copy方法最为简洁,并且耗时最短,但是这并不能表示以后只用这种方法来复制文件,因为在测试的时候自己设置的缓冲区是1M的,如果选取适当的缓冲区,性能会比较高效,所以我们可以因地制宜的选用这四种方法。