NIO学习
N IO简介
NIO与IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区,基于通道
的IO操作,NIO能以更高效的方式读写操作。
NIO的工作原理
NIO有缓冲区(buffer一个数据容器)和通道(Channel)
简而言之好比 运送一批货物,通道是车道,缓冲区是车厢,货物的到达就是数据的传递
NIO读写数据
String s="sgsgs";
ByteBuffer allocate = ByteBuffer.allocate(10);
//放入数据
allocate.put(s.getBytes());
//读取数据
allocate.flip();
byte[] bytes = new byte[allocate.limit()];
//读取数据
allocate.get(bytes,0,2);
System.out.println(allocate.position());
//标记
allocate.mark();
//再次读取数据
allocate.get(bytes,2,3);
//回到上次指针标记的position位置用 reset()方法
allocate.reset();
用NIO复制数据方式
- 方式一
(1)用fileOutputstream和FileInputStream读取
(2)构建getChannel通道
FileInputStream in = new FileInputStream("file.txt");
FileOutputStream out = new FileOutputStream("file2.txt");
//构建缓冲区通道
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (inChannel.read(byteBuffer)!=-1){
byteBuffer.flip();
outChannel.write(byteBuffer);
//清空缓冲区
byteBuffer.clear();
}
inChannel.close();
outChannel.close();
in.close();
out.close();
-
方式二
通过FileChannel中的静态方法 open()可以打开一个通道
FileChannel in= FileChannel.open(Paths.get("file.txt"), StandardOpenOption.READ); FileChannel out = FileChannel.open(Paths.get("file2.ts"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); ByteBuffer allocate = ByteBuffer.allocate(1024 * 1024); while (in.read(allocate)!=-1){ //切换读取模式 allocate.flip(); out.write(allocate); allocate.clear(); } in.close(); out.close();FileChannel in= FileChannel.open(Paths.get("歌曲串烧.mp3"), StandardOpenOption.READ); FileChannel.open(Paths.get("file2.ts"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);