NIO之轻松读取大文件

011-01-07 13:44 来自 admin NIO轻松读取大文件(1G以上)

01 import java.io.FileInputStream;
02 import java.io.FileOutputStream;
03 import java.io.IOException;
04 import java.nio.ByteBuffer;
05 import java.nio.channels.FileChannel;
06 /**
07   *
08   * 用NIO读取大文本(1G以上)
09   *
10   * @author landon
11   *
12   */
13 public class ReadLargeTextWithNIO
14 {
15   public static void main(String...args) throws IOException
16   {
17    FileInputStream fin = new FileInputStream( "d:\\temp\\outlineA1.log" );
18    FileChannel fcin = fin.getChannel();
19     
20    ByteBuffer buffer = ByteBuffer.allocate( 1024 * 1024 * 50 );
21     
22    while ( true )
23    {
24     buffer.clear();
25      
26     int flag = fcin.read(buffer);
27      
28     if (flag == - 1 )
29     {
30      break ;
31     }
32      
33     buffer.flip();
34      
35     FileOutputStream fout = new FileOutputStream( "d:\\temp\\" + Math.random() + ".log" );
36     FileChannel fcout = fout.getChannel();
37      
38     fcout.write(buffer);
39    }
40   }
41 }
42  
43 下面简单说几个注意的地方:
44 a.因为要把超大文本切分成小的部分,所以分配buffer的时候尽量大一些,这里我分配的大小是50M,不过如果太大了,可能会报内存溢出。
45 b.说一下clear和flip的方法,直接上源码:
46 public final Buffer clear()
47 {
48 position = 0 ;
49 limit = capacity;
50 mark = - 1 ;
51 return this ;
52 }
53  
54 public final Buffer flip()
55 {
56 limit = position;
57 position = 0 ;
58 mark = - 1 ;
59 return this ;
60 }
61 一看便知二者的区别。
62 c.跳出循环也即读完的判断是read返回的flag是- 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值