NIO⼊门之轻松读取⼤⽂件
今天同事碰到了⼀个问题,从游戏服务器下载下来的输出log有⼀个多G⼤。⽤记事本打不开,EditPlus也打不开,都提⽰⽂件太⼤。⽤word也打不开,提⽰⽂件⼤于512M。打不开怎么查找错误啊。于是他问我解决办法。我想了想,决定写⼀个简单的程序读取这个log,把这个log切分成⼀些⼩的可以⽤Editplus打开的⽂本。正好前段时间看了⼀些NIO的东西,所以决定⽤NIO来写。没想到,10⼏⾏代码就搞定了。下⾯附上源代码:
ReadLargeTextWithNIO.java 1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637383940414243444546
package com.nio.entrace;
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;/** *
* ⽤NIO读取⼤⽂本(1G以上) *
* @author landon * */
public class ReadLargeTextWithNIO {
public static void main(Stringargs) throws IOException {
FileInputStream fin = new FileInputStream(\"d:\\\emp\\\\outlineA1.log\"); FileChannel fcin = fin.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 50);
while(true) {
buffer.clear();
int flag = fcin.read(buffer);
if(flag == -1) {
break; }
buffer.flip();
FileOutputStream fout = new FileOutputStream(\"d:\\\emp\\\\\" + Math.random() + \".log\"); FileChannel fcout = fout.getChannel();
fcout.write(buffer); } }}
下⾯简单说⼏个注意的地⽅:
a.因为要把超⼤⽂本切分成⼩的部分,所以分配buffer的时候尽量⼤⼀些,这⾥我分配的⼤⼩是50M,不过如果太⼤了,可能会报内存溢出。
b.说⼀下clear和flip的⽅法,直接上源码: 1 2 3 4 5 6
public final Buffer clear() {
position = 0; limit = capacity; mark = -1; return this;
7 8 9101112131415
}
public final Buffer flip() {
limit = position; position = 0; mark = -1; return this; }
⼀看便知⼆者的区别。
c.跳出循环也即读完的判断是read返回的flag是-1 利⽤NIO确实⽅便,以后继续研究->NIO⽹络编程