1. 程式人生 > >java檔案流讀寫操作

java檔案流讀寫操作

優化BufferedRandomAccessFile。

優化原則:

  •     呼叫頻繁的語句最需要優化,且優化的效果最明顯。
  •     多重巢狀邏輯判斷時,最可能出現的判斷,應放在最外層。
  •     減少不必要的NEW。


這裡舉一典型的例子:

Java程式碼  收藏程式碼
  1. publicvoid seek(long pos) throws IOException {  
  2. ...  
  3.        this.bufstartpos =  pos * bufbitlen / bufbitlen; // bufbitlen指buf[]的位長,例:若bufsize=1024,則bufbitlen=10。
  4.               ...  
  5. }  
 

seek函式使用在各函式中,呼叫非常頻繁,上面加重的這行語句根據pos和bufsize確定buf[]對應當前檔案的對映位置,用"*"、"/"確定,顯然不是一個好方法。

  • 優化一:this.bufstartpos = (pos << bufbitlen) >> bufbitlen;
  • 優化二:this.bufstartpos = pos & bufmask; // this.bufmask = ~((long)this.bufsize - 1);

兩者效率都比原來好,但後者顯然更好,因為前者需要兩次移位運算、後者只需一次邏輯與運算(bufmask可以預先得出)。

至此優化基本實現,逐位元組COPY一個12兆的檔案,(這裡牽涉到讀和寫,結合緩衝讀,用優化後BufferedRandomAccessFile試一下讀/寫的速度):

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

可見優化儘管不明顯,還是比未優化前快了一些,也許這種效果在老式機上會更明顯。

以上比較的是順序存取,即使是隨機存取,在絕大多數情況下也不止一個BYTE,所以緩衝機制依然有效。而一般的順序存取類要實現隨機存取就不怎麼容易了。

需要完善的地方

提供檔案追加功能:

Java程式碼  收藏程式碼
  1. publicboolean append(byte bw) throws IOException {  
  2.    returnthis.write(bw, this.fileendpos + 1);  
  3. }  

提供檔案當前位置修改功能:

Java程式碼  收藏程式碼
  1. publicboolean write(byte bw) throws IOException {  
  2.    returnthis.write(bw, this.curpos);  
  3. }  

返回檔案長度(由於BUF讀寫的原因,與原來的RandomAccessFile類有所不同):

Java程式碼  收藏程式碼
  1. publiclong length() throws IOException {  
  2.    returnthis.max(this.fileendpos + 1this.initfilelen);  
  3. }  

返回檔案當前指標(由於是通過BUF讀寫的原因,與原來的RandomAccessFile類有所不同):

Java程式碼  收藏程式碼
  1. publiclong getFilePointer() throws IOException {  
  2.    returnthis.curpos;  
  3. }  

提供對當前位置的多個位元組的緩衝寫功能:

Java程式碼  收藏程式碼
  1. publicvoid write(byte b[], int off, int len) throws IOException {  
  2.         long writeendpos = this.curpos + len - 1;  
  3.         if (writeendpos <= this.bufendpos) { // b[] in cur buf
  4.             System.arraycopy(b, off, this.buf, (int)(this.curpos - this.bufstartpos), len);  
  5.             this.bufdirty = true;  
  6.             this.bufusedsize = (int)(writeendpos - this.bufstartpos + 1);  
  7.         } else { // b[] not in cur buf
  8.             super.seek(this.curpos);  
  9.             super.write(b, off, len);  
  10.         }  
  11.         if (writeendpos > this.fileendpos)  
  12.             this.fileendpos = writeendpos;  
  13.         this.seek(writeendpos+1);  
  14. }  
  15. publicvoid write(byte b[]) throws IOException {  
  16.         this.write(b, 0, b.length);  
  17. }  

提供對當前位置的多個位元組的緩衝讀功能:

Java程式碼  收藏程式碼
  1. publicint read(byte b[], int off, int len) throws IOException {  
  2.     long readendpos = this.curpos + len - 1;  
  3.     if (readendpos <= this.bufendpos && readendpos <= this.fileendpos ) { // read in buf
  4.         System.arraycopy(this.buf, (int)(this.curpos - this.bufstartpos), b, off, len);  
  5.     } else { // read b[] size > buf[]
  6.     if (readendpos > this.fileendpos) { // read b[] part in file
  7.         len = (int)(this.length() - this.curpos + 1);  
  8.     }  
  9.        super.seek(this.curpos);  
  10.        len = super.read(b, off, len);  
  11.        readendpos = this.curpos + len - 1;  
  12.    }  
  13.        this.seek(readendpos + 1);  
  14.        return len;  
  15. }  
  16. publicint read(byte b[]) throws IOException {  
  17.    returnthis.read(b, 0, b.length);  
  18. }  
  19. publicvoid setLength(long newLength) throws IOException {  
  20.    if (newLength > 0) {  
  21.        this.fileendpos = newLength - 1;  
  22.    } else {  
  23.        this.fileendpos = 0;  
  24.    }  
  25.    super.setLength(newLength);  
  26. }  
  27. publicvoid close() throws IOException {  
  28.    this.flushbuf();  
  29.    super.close();  
  30. }  
 

至此完善工作基本完成,試一下新增的多位元組讀/寫功能,通過同時讀/寫1024個位元組,來COPY一個12兆的檔案,(這裡牽涉到讀和寫,用完善後BufferedRandomAccessFile試一下讀/寫的速度):

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

與MappedByteBuffer+RandomAccessFile的對比?

JDK1.4+提供了NIO類 ,其中MappedByteBuffer類用於對映緩衝,也可以對映隨機檔案訪問,可見JAVA設計者也看到了RandomAccessFile的問題,並加以改進。怎麼通過MappedByteBuffer+RandomAccessFile拷貝檔案呢?下面就是測試程式的主要部分:

Java程式碼  收藏程式碼
  1. RandomAccessFile rafi = new RandomAccessFile(SrcFile, "r");  
  2. RandomAccessFile rafo = new RandomAccessFile(DesFile, "rw");  
  3. FileChannel fci = rafi.getChannel();  
  4. FileChannel fco = rafo.getChannel();  
  5. long size = fci.size();  
  6. MappedByteBuffer mbbi = fci.map(FileChannel.MapMode.READ_ONLY, 0, size);  
  7. MappedByteBuffer mbbo = fco.map(FileChannel.MapMode.READ_WRITE, 0, size);  
  8. long start = System.currentTimeMillis();  
  9. for (int i = 0; i < size; i++) {  
  10.     byte b = mbbi.get(i);  
  11.     mbbo.put(i, b);  
  12. }  
  13. fcin.close();  
  14. fcout.close();  
  15. rafi.close();  
  16. rafo.close();  
  17. System.out.println("Spend: "+(double)(System.currentTimeMillis()-start) / 1000 + "s");  
 

試一下JDK1.4的對映緩衝讀/寫功能,逐位元組COPY一個12兆的檔案,(這裡牽涉到讀和寫):

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

確實不錯,看來NIO有了極大的進步。建議採用 MappedByteBuffer+RandomAccessFile的方式。