健康的程序员

导航

Buffer、Channel示例

 

a.txt

孔雀向西飞,今朝更好看。
孔雀向西飞,今朝更好看。
孔雀向西飞,今朝更好看。
孔雀向西飞,今朝更好看。

示例一、

 1 package com.test;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.nio.ByteBuffer;
 6 import java.nio.channels.FileChannel;
 7 
 8 public class Main {
 9     public static void main(String[] args) throws Exception {
10         FileInputStream fis = new FileInputStream("E://a.txt");
11         FileOutputStream fos = new FileOutputStream("E://b.txt");
12         FileChannel in = fis.getChannel();
13         FileChannel out = fos.getChannel();
14         ByteBuffer buf = ByteBuffer.allocateDirect(20);
15         while (true) {
16             // 从通道in中读数据到buf,然后从buf中读出来写入out通道
17             int eof = in.read(buf);
18             if (eof == -1)
19                 break;
20             buf.flip();
21             int c = out.write(buf);
22             System.out.println("c=" + c);
23             buf.clear();
24         }
25         fis.close();
26         fos.close();28     }
29 }

执行结果
b.txt

孔雀向西飞,今朝更好看。
孔雀向西飞,今朝更好看。
孔雀向西飞,今朝更好看。
孔雀向西飞,今朝更好看。

示例二、
 1 package com.test;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.nio.ByteBuffer;
 6 import java.nio.channels.FileChannel;
 7 
 8 public class Main {
 9     public static void main(String[] args) throws Exception {
10         FileInputStream fis = new FileInputStream("E://a.txt");
11         FileOutputStream fos = new FileOutputStream("E://b.txt");
12         FileOutputStream fos2 = new FileOutputStream("E://c.txt");
13         FileChannel in = fis.getChannel();
14         FileChannel out = fos.getChannel();
15         FileChannel out2 = fos2.getChannel();
16         ByteBuffer buf = ByteBuffer.allocateDirect(20);
17         ByteBuffer buf2 = ByteBuffer.allocateDirect(20);
18         while (true) {
19             // 从通道in中读数据到buf,然后从buf中读出来写入out通道
20             int eof = in.read(buf);
21             if (eof == -1)
22                 break;
23             buf.flip();
24             int c = out.write(buf);
25             System.out.println("c=" + c);
26             buf.clear();
27             // 从通道in中读数据到buf,然后从buf中读出来写入out2通道
28             int eof2 = in.read(buf2);
29             if (eof2 == -1)
30                 break;
31             buf2.flip();
32             int c2 = out2.write(buf2);
33             System.out.println("c2=" + c2);
34             buf2.clear();
35         }
36         fis.close();
37         fos.close();
38         fos2.close();
39     }
40 }

执行结果

b.txt

孔雀向西飞,今朝更好朝更好看。
孔雀向西雀向西飞,今朝更好看

c.txt

看。
孔雀向西飞,今飞,今朝更好看。
孔。



 

posted on 2015-08-04 20:08  健康的程序员  阅读(125)  评论(0编辑  收藏  举报