这两天用RandomAccessFile的readLine读取.log文件,不管怎样处理读出来的line都是乱码,无奈之下只能自己实现一个readLine方法,先读出bytes

再判断是否换行,一行一行的读出,注意filePointer的变化。

参考:http://hi.baidu.com/nathena/item/84f33079fa457b3a71442397

package com.dhcc.logtailer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class MyRandomAccessFile {
    
    private RandomAccessFile file;
    private byte[] b;
    private String charSet;
    private long filePointer;
    
    public MyRandomAccessFile(File file,String mode,String charSet) throws FileNotFoundException{
        this.file = new RandomAccessFile(file,mode);
        this.charSet = charSet;
    }
    public void seek(long pos) throws IOException{        
        this.file.seek(pos);
    }
    public long getFilePointer() throws IOException{
        return this.file.getFilePointer();
    }
    public void close() throws IOException{
        this.file.close();
    }

    public String readLine() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int size = 0;
        boolean ifCRLF = false;
        int read = 0; // 已读数
        while (true) {
            // 填充byte[]
            fill();
            size = b.length;
            if(b.length==0){
                   return null;
               }
            for (int i = 0; i < size; i++) {
                read++;
                if (b[i] == '\n') {
                    ifCRLF = true;
                    break;
                }
                if (b[i] != '\r') {
                    baos.write(b[i]);
                }
            }

            // 重置b
            b = Arrays.copyOfRange(b, read, size);
            if (ifCRLF)
                break;
        }

        byte[] b = baos.toByteArray();
        file.seek(this.filePointer+read);
        baos.close();// ByteArrayOutputStream close无用。
        baos = null;
        return new String(b, charSet);
    }
    
    private void fill() throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (b != null && b.length > 0) {
            baos.write(b, 0, b.length);
        }
        int size = 0;
        long filelength = file.length();
        long filepointer = file.getFilePointer();
        if(filepointer>=filelength){
            b = new byte[0];
            return;
        }
        byte[] _b = new byte[(int) (filelength - filepointer)];        
        this.filePointer = file.getFilePointer();
        size = file.read(_b);
        baos.write(_b, 0, size);
        _b = null;
        b = baos.toByteArray();
        baos = null;
    }
}

 

 posted on 2013-10-14 17:40  几经浮沉  阅读(1334)  评论(0)    收藏  举报