nio的分散和彙集讀寫

 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 }
相關文章
相關標籤/搜索