高效率讀取大文件進(jìn)行數(shù)據(jù)處理-通過(guò)擴(kuò)展RandomAccessFile類使之具備Buffer改善I/O性能

開(kāi)發(fā)人員需文件隨機(jī)存取,就得使用RandomAccessFile類。其I/O性能較之其它常用開(kāi)發(fā)語(yǔ)言的同類性能差距甚遠(yuǎn),嚴(yán)重影響程序的運(yùn)行效率。

開(kāi)發(fā)人員迫切需要提高效率,下面分析RandomAccessFile等文件類的源代碼,找出其中的癥結(jié)所在,并加以改進(jìn)優(yōu)化,創(chuàng)建一個(gè)"性/價(jià)比"俱佳的隨機(jī)文件訪問(wèn)類BufferedRandomAccessFile。
在改進(jìn)之前先做一個(gè)基本測(cè)試:逐字節(jié)COPY一個(gè)12兆的文件(這里牽涉到讀和寫)。

耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935

我們可以看到兩者差距約32倍,RandomAccessFile也太慢了。先看看兩者關(guān)鍵部分的源代碼,對(duì)比分析,找出原因。

1.1.[RandomAccessFile]

public class RandomAccessFile implements DataOutput, DataInput {
    public final byte readByte() throws IOException {
        int ch = this.read();
        if (ch < 0)
            throw new EOFException();
        return (byte)(ch);
    }
    public native int read() throws IOException; 
    public final void writeByte(int v) throws IOException {
        write(v);
    }
    public native void write(int b) throws IOException; 
}

可見(jiàn),RandomAccessFile每讀/寫一個(gè)字節(jié)就需對(duì)磁盤進(jìn)行一次I/O操作。

1.2.[BufferedInputStream]

public class BufferedInputStream extends FilterInputStream {
    private static int defaultBufferSize = 2048; 
    protected byte buf[]; // 建立讀緩存區(qū)
    public BufferedInputStream(InputStream in, int size) {
        super(in);       
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }
    public synchronized int read() throws IOException {
        ensureOpen();
        if (pos >= count) {
            fill();
            if (pos >= count)
                return -1;
        }
        return buf[pos++] & 0xff; // 直接從BUF[]中讀取
    }
    private void fill() throws IOException {
    if (markpos < 0)
        pos= 0;        /* no mark: throw away the buffer */
    else if (pos >= buf.length)  /* no room left in buffer */
        if (markpos > 0) {   /* can throw away early part of the buffer */
        int sz = pos - markpos;
        System.arraycopy(buf, markpos, buf, 0, sz);
        pos = sz;
        markpos = 0;
        } else if (buf.length >= marklimit) {
        markpos = -1;   /* buffer got too big, invalidate mark */
        pos = 0;    /* drop buffer contents */
        } else {        /* grow buffer */
        int nsz = pos * 2;
        if (nsz > marklimit)
            nsz = marklimit;
        byte nbuf[] = new byte[nsz];
        System.arraycopy(buf, 0, nbuf, 0, pos);
        buf = nbuf;
        }
    count = pos;
    int n = in.read(buf, pos, buf.length - pos);
    if (n > 0)
        count = n + pos;
    }
}

1.3.[BufferedOutputStream]

public class BufferedOutputStream extends FilterOutputStream {
   protected byte buf[]; // 建立寫緩存區(qū)
   public BufferedOutputStream(OutputStream out, int size) {
        super(out);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }
public synchronized void write(int b) throws IOException {
        if (count >= buf.length) {
            flushBuffer();
        }
        buf[count++] = (byte)b; // 直接從BUF[]中讀取
   }
   private void flushBuffer() throws IOException {
        if (count > 0) {
            out.write(buf, 0, count);
            count = 0;
        }
   }
}

可見(jiàn),Buffered I/O putStream每讀/寫一個(gè)字節(jié),若要操作的數(shù)據(jù)在BUF中,就直接對(duì)內(nèi)存的buf[]進(jìn)行讀/寫操作;否則從磁盤相應(yīng)位置填充buf[],再直接對(duì)內(nèi)存的buf[]進(jìn)行讀/寫操作,絕大部分的讀/寫操作是對(duì)內(nèi)存buf[]的操作。

1.3.小結(jié)

內(nèi)存存取時(shí)間單位是納秒級(jí)(10E-9),磁盤存取時(shí)間單位是毫秒級(jí)(10E-3), 同樣操作一次的開(kāi)銷,內(nèi)存比磁盤快了百萬(wàn)倍。理論上可以預(yù)見(jiàn),即使對(duì)內(nèi)存操作上萬(wàn)次,花費(fèi)的時(shí)間也遠(yuǎn)少對(duì)于磁盤一次I/O的開(kāi)銷。 顯然后者是通過(guò)增加位于內(nèi)存的BUF存取,減少磁盤I/O的開(kāi)銷,提高存取效率的,當(dāng)然這樣也增加了BUF控制部分的開(kāi)銷。從實(shí)際應(yīng)用來(lái)看,存取效率提高了32倍。

根據(jù)1.3得出的結(jié)論,現(xiàn)試著對(duì)RandomAccessFile類也加上緩沖讀寫機(jī)制。
隨機(jī)訪問(wèn)類與順序類不同,前者是通過(guò)實(shí)現(xiàn)DataInput/DataOutput接口創(chuàng)建的,而后者是擴(kuò)展FilterInputStream/FilterOutputStream創(chuàng)建的,不能直接照搬。

2.1.開(kāi)辟緩沖區(qū)BUF[默認(rèn):1024字節(jié)],用作讀/寫的共用緩沖區(qū)。

2.2.先實(shí)現(xiàn)讀緩沖。

讀緩沖邏輯的基本原理:

A 欲讀文件POS位置的一個(gè)字節(jié)。

B 查BUF中是否存在?若有,直接從BUF中讀取,并返回該字符BYTE。

C 若沒(méi)有,則BUF重新定位到該P(yáng)OS所在的位置并把該位置附近的BUFSIZE的字節(jié)的文件內(nèi)容填充BUFFER,返回B。

以下給出關(guān)鍵部分代碼及其說(shuō)明:

public class BufferedRandomAccessFile extends RandomAccessFile {
//  byte read(long pos):讀取當(dāng)前文件POS位置所在的字節(jié)
//  bufstartpos、bufendpos代表BUF映射在當(dāng)前文件的首/尾偏移地址。
//  curpos指當(dāng)前類文件指針的偏移地址。
    public byte read(long pos) throws IOException {
        if (pos < this.bufstartpos|| pos > this.bufendpos ) {
            this.flushbuf();
            this.seek(pos);
            if ((pos < this.bufstartpos) || (pos > this.bufendpos)) 
                throw new IOException();
        }
        this.curpos = pos;
        return this.buf[(int)(pos - this.bufstartpos)];
    }
// void flushbuf():bufdirty為真,把buf[]中尚未寫入磁盤的數(shù)據(jù),寫入磁盤。
    private void flushbuf() throws IOException {
        if (this.bufdirty == true) {
            if (super.getFilePointer() != this.bufstartpos) {
                super.seek(this.bufstartpos);
            }
            super.write(this.buf, 0, this.bufusedsize);
            this.bufdirty = false;
        }
    }
// void seek(long pos):移動(dòng)文件指針到pos位置,并把buf[]映射填充至POS
所在的文件塊。
    public void seek(long pos) throws IOException {
        if ((pos < this.bufstartpos) || (pos > this.bufendpos)) { // seek pos not in buf
            this.flushbuf();
            if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0)) 
{   // seek pos in file (file length > 0)
                  this.bufstartpos =  pos * bufbitlen / bufbitlen;
                this.bufusedsize = this.fillbuf();
            } else if (((pos == 0) && (this.fileendpos == 0)) 
|| (pos == this.fileendpos + 1)) 
{   // seek pos is append pos
                this.bufstartpos = pos;
                this.bufusedsize = 0;
            }
            this.bufendpos = this.bufstartpos + this.bufsize - 1;
        }
        this.curpos = pos;
    }
// int fillbuf():根據(jù)bufstartpos,填充buf[]。
    private int fillbuf() throws IOException {
        super.seek(this.bufstartpos);
        this.bufdirty = false;
        return super.read(this.buf);
    }
}

至此緩沖讀基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件(這里牽涉到讀和寫,用BufferedRandomAccessFile試一下讀的速度):

耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935

可見(jiàn)速度顯著提高,與BufferedInputStream+DataInputStream不相上下。

2.3.實(shí)現(xiàn)寫緩沖。

寫緩沖邏輯的基本原理:

A欲寫文件POS位置的一個(gè)字節(jié)。

B 查BUF中是否有該映射?若有,直接向BUF中寫入,并返回true。

C若沒(méi)有,則BUF重新定位到該P(yáng)OS所在的位置,并把該位置附近的 BUFSIZE字節(jié)的文件內(nèi)容填充BUFFER,返回B。

下面給出關(guān)鍵部分代碼及其說(shuō)明:

// boolean write(byte bw, long pos):向當(dāng)前文件POS位置寫入字節(jié)BW。
// 根據(jù)POS的不同及BUF的位置:存在修改、追加、BUF中、BUF外等情
況。在邏輯判斷時(shí),把最可能出現(xiàn)的情況,最先判斷,這樣可提高速度。
// fileendpos:指示當(dāng)前文件的尾偏移地址,主要考慮到追加因素
    public boolean write(byte bw, long pos) throws IOException {
        if ((pos >= this.bufstartpos) && (pos <= this.bufendpos)) { 
// write pos in buf
            this.buf[(int)(pos - this.bufstartpos)] = bw;
            this.bufdirty = true;
            if (pos == this.fileendpos + 1) { // write pos is append pos
                this.fileendpos++;
                this.bufusedsize++;
            }
        } else { // write pos not in buf
            this.seek(pos);
            if ((pos >= 0) && (pos <= this.fileendpos) && (this.fileendpos != 0)) 
{ // write pos is modify file
                this.buf[(int)(pos - this.bufstartpos)] = bw;
            } else if (((pos == 0) && (this.fileendpos == 0)) 
|| (pos == this.fileendpos + 1)) { // write pos is append pos
                this.buf[0] = bw;
                this.fileendpos++;
                this.bufusedsize = 1;
            } else {
                throw new IndexOutOfBoundsException();
            }
            this.bufdirty = true;
        }
        this.curpos = pos;
        return true;
    }

至此緩沖寫基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫,結(jié)合緩沖讀,用BufferedRandomAccessFile試一下讀/寫的速度):

耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453

可見(jiàn)綜合讀/寫速度已超越BufferedInput/OutputStream+DataInput/OutputStream。

優(yōu)化BufferedRandomAccessFile。
優(yōu)化原則:

調(diào)用頻繁的語(yǔ)句最需要優(yōu)化,且優(yōu)化的效果最明顯。
多重嵌套邏輯判斷時(shí),最可能出現(xiàn)的判斷,應(yīng)放在最外層。
減少不必要的NEW。
這里舉一典型的例子:

public void seek(long pos) throws IOException {
        ...
this.bufstartpos =  pos * bufbitlen / bufbitlen; 
// bufbitlen指buf[]的位長(zhǎng),例:若bufsize=1024,則bufbitlen=10。
...
}

seek函數(shù)使用在各函數(shù)中,調(diào)用非常頻繁,上面加重的這行語(yǔ)句根據(jù)pos和bufsize確定buf[]對(duì)應(yīng)當(dāng)前文件的映射位置,用"*"、"/"確定,顯然不是一個(gè)好方法。

優(yōu)化一:this.bufstartpos = (pos << bufbitlen) >> bufbitlen;

優(yōu)化二:this.bufstartpos = pos & bufmask; // this.bufmask = ~((long)this.bufsize - 1);

兩者效率都比原來(lái)好,但后者顯然更好,因?yàn)榍罢咝枰獌纱我莆贿\(yùn)算、后者只需一次邏輯與運(yùn)算(bufmask可以預(yù)先得出)。

至此優(yōu)化基本實(shí)現(xiàn),逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫,結(jié)合緩沖讀,用優(yōu)化后BufferedRandomAccessFile試一下讀/寫的速度):

耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453
BufferedRandomAccessFile優(yōu) BufferedRandomAccessFile優(yōu) 2.197

可見(jiàn)優(yōu)化盡管不明顯,還是比未優(yōu)化前快了一些,也許這種效果在老式機(jī)上會(huì)更明顯。

以上比較的是順序存取,即使是隨機(jī)存取,在絕大多數(shù)情況下也不止一個(gè)BYTE,所以緩沖機(jī)制依然有效。而一般的順序存取類要實(shí)現(xiàn)隨機(jī)存取就不怎么容易了。

需要完善的地方
提供文件追加功能:

public boolean append(byte bw) throws IOException {
    return this.write(bw, this.fileendpos + 1);
}

提供文件當(dāng)前位置修改功能:

public boolean write(byte bw) throws IOException {
    return this.write(bw, this.curpos);
}

返回文件長(zhǎng)度(由于BUF讀寫的原因,與原來(lái)的RandomAccessFile類有所不同):

public long length() throws IOException {
    return this.max(this.fileendpos + 1, this.initfilelen);
}

返回文件當(dāng)前指針(由于是通過(guò)BUF讀寫的原因,與原來(lái)的RandomAccessFile類有所不同):

public long getFilePointer() throws IOException {
return this.curpos;
}

提供對(duì)當(dāng)前位置的多個(gè)字節(jié)的緩沖寫功能:

public void write(byte b[], int off, int len) throws IOException {
        long writeendpos = this.curpos + len - 1;
        if (writeendpos <= this.bufendpos) { // b[] in cur buf
System.arraycopy(b, off, this.buf, (int)(this.curpos - this.bufstartpos), 
len);
            this.bufdirty = true;
            this.bufusedsize = (int)(writeendpos - this.bufstartpos + 1);
        } else { // b[] not in cur buf
            super.seek(this.curpos);
            super.write(b, off, len);
        }
        if (writeendpos > this.fileendpos)
            this.fileendpos = writeendpos;
        this.seek(writeendpos+1);
}
    public void write(byte b[]) throws IOException {
        this.write(b, 0, b.length);
    }

提供對(duì)當(dāng)前位置的多個(gè)字節(jié)的緩沖讀功能:

public int read(byte b[], int off, int len) throws IOException {
long readendpos = this.curpos + len - 1;
   if (readendpos <= this.bufendpos && readendpos <= this.fileendpos ) { 
// read in buf
        System.arraycopy(this.buf, (int)(this.curpos - this.bufstartpos), 
b, off, len);
   } else { // read b[] size > buf[]
        if (readendpos > this.fileendpos) { // read b[] part in file
            len = (int)(this.length() - this.curpos + 1);
       }
       super.seek(this.curpos);
       len = super.read(b, off, len);
       readendpos = this.curpos + len - 1;
   }
       this.seek(readendpos + 1);
       return len;
}
   public int read(byte b[]) throws IOException {
        return this.read(b, 0, b.length);
   }
public void setLength(long newLength) throws IOException {
        if (newLength > 0) {
            this.fileendpos = newLength - 1;
        } else {
            this.fileendpos = 0;
        }
        super.setLength(newLength);
}
     
public void close() throws IOException {
        this.flushbuf();
        super.close();
    }

至此完善工作基本完成,試一下新增的多字節(jié)讀/寫功能,通過(guò)同時(shí)讀/寫1024個(gè)字節(jié),來(lái)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫,用完善后BufferedRandomAccessFile試一下讀/寫的速度):

耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453
BufferedRandomAccessFile優(yōu) BufferedRandomAccessFile優(yōu) 2.197
BufferedRandomAccessFile完 BufferedRandomAccessFile完 0.401

與JDK1.4新類MappedByteBuffer+RandomAccessFile的對(duì)比?
JDK1.4提供了NIO類 ,其中MappedByteBuffer類用于映射緩沖,也可以映射隨機(jī)文件訪問(wèn),可見(jiàn)JAVA設(shè)計(jì)者也看到了RandomAccessFile的問(wèn)題,并加以改進(jìn)。怎么通過(guò)MappedByteBuffer+RandomAccessFile拷貝文件呢?下面就是測(cè)試程序的主要部分:

RandomAccessFile rafi = new RandomAccessFile(SrcFile, "r");
   RandomAccessFile rafo = new RandomAccessFile(DesFile, "rw");
    FileChannel fci = rafi.getChannel();
FileChannel fco = rafo.getChannel();
    long size = fci.size();
    MappedByteBuffer mbbi = fci.map(FileChannel.MapMode.READ_ONLY, 0, size);
MappedByteBuffer mbbo = fco.map(FileChannel.MapMode.READ_WRITE, 0, size);
long start = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
            byte b = mbbi.get(i);
            mbbo.put(i, b);
}
fcin.close();
fcout.close();
rafi.close();
rafo.close();
System.out.println("Spend: "+(double)(System.currentTimeMillis()-start) / 1000 + "s");

試一下JDK1.4的映射緩沖讀/寫功能,逐字節(jié)COPY一個(gè)12兆的文件,(這里牽涉到讀和寫):

耗用時(shí)間(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
BufferedRandomAccessFile BufferedRandomAccessFile 2.453
BufferedRandomAccessFile優(yōu) BufferedRandomAccessFile優(yōu) 2.197
BufferedRandomAccessFile完 BufferedRandomAccessFile完 0.401
MappedByteBuffer+ RandomAccessFile MappedByteBuffer+ RandomAccessFile 1.209

確實(shí)不錯(cuò),看來(lái)JDK1.4比1.3有了極大的進(jìn)步。如果以后采用1.4版本開(kāi)發(fā)軟件時(shí),需要對(duì)文件進(jìn)行隨機(jī)訪問(wèn),建議采用MappedByteBuffer+RandomAccessFile的方式。但鑒于目前采用JDK1.3及以前的版本開(kāi)發(fā)的程序占絕大多數(shù)的實(shí)際情況,如果您開(kāi)發(fā)的JAVA程序使用了RandomAccessFile類來(lái)隨機(jī)訪問(wèn)文件,并因其性能不佳,而擔(dān)心遭用戶詬病,請(qǐng)?jiān)囉帽疚乃峁┑腂ufferedRandomAccessFile類,不必推翻重寫,只需IMPORT 本類,把所有的RandomAccessFile改為BufferedRandomAccessFile,您的程序的性能將得到極大的提升,您所要做的就這么簡(jiǎn)單。

未來(lái)的考慮
讀者可在此基礎(chǔ)上建立多頁(yè)緩存及緩存淘汰機(jī)制,以應(yīng)付對(duì)隨機(jī)訪問(wèn)強(qiáng)度大的應(yīng)用。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容