代码改变世界

nio的分散和聚集读写

2018-09-12 17:28  kill-9  阅读(280)  评论(0编辑  收藏  举报
 1 package edzy.nio;
 2 
 3 
 4 import java.io.IOException;
 5 import java.io.RandomAccessFile;
 6 import java.nio.ByteBuffer;
 7 import java.nio.channels.FileChannel;
 8 
 9 /*
10 
11  * 分散和聚集
12  * 
13  */
14 public class Gather {
15 
16     public static void main(String[] args) throws IOException {
17 
18         RandomAccessFile  fin = new RandomAccessFile("./src/main/java/edzy/nio/centos7.txt","rw");
19         FileChannel in = fin.getChannel();
20 
21         //分配多个指定大小的缓存区
22         ByteBuffer buf1 = ByteBuffer.allocate(512);
23         ByteBuffer buf2 = ByteBuffer.allocate(1024);
24        // ByteBuffer buf3 = ByteBuffer.allocate(1024);
25 
26         //分离读取
27         ByteBuffer[] buffers = {buf1,buf2};
28         in.read(buffers);
29 
30         for (ByteBuffer buf : buffers){
31             buf.flip();
32             System.out.println(new String (buf.array(),0,buf.limit()));
33             System.out.println("########################################");
34             buf.clear();
35 
36         }
37 
38         RandomAccessFile fout = new RandomAccessFile("./centos.txt","rw");
39         FileChannel out = fout.getChannel();
40         out.write(buffers);
41 
42         out.close();
43         in.close();
44         fout.close();
45         fin.close();
46 
47 
48     }
49 }