1. 程式人生 > >java 完美讀取位元組流 例項

java 完美讀取位元組流 例項

在使用BufferedInputStream讀取位元組流是,若最後剩餘的位元組數,小於指定讀取的位元組數,則返回的位元組陣列的內容長度仍然是指定的位元組數,這時若寫入新的檔案,或者寫

入socket時,則會出現目標檔案比原檔案多幾個位元組,並不是和原檔案一模一樣的大小。下面的例子可以完美的解決這個問題。^_^

  1. @Override
  2. publicvoid run() {  
  3.     try {  
  4.         FileInputStream fis = null;  
  5.         BufferedInputStream bis = null;  
  6.         fis = new
     FileInputStream(filepath);  
  7.         if (fis != null) {  
  8.             bis = new BufferedInputStream(fis);  
  9.         }  
  10.         if (bis != null) {  
  11.             byte[] bs = newbyte[512];    
  12.             while(bis.available() > 512) {  
  13.                 bis.read(bs);  
  14.                 ByteBuffer src = ByteBuffer.wrap(bs);  
  15.                 // write data to client socket channel
  16.                 lsockChannel.write(src);  
  17.                 Arrays.fill(bs, (byte)0);  
  18.             }  
  19.             // 處理不足512的剩餘部分
  20.             int remain = bis.available();   
  21.             byte[] last = newbyte[remain];  
  22.             bis.read(last);  
  23.             lsockChannel.write(ByteBuffer.wrap(last));  
  24.             bis.close();  
  25.             fis.close();  
  26.             lsockChannel.close();  
  27.         }  
  28.     } catch (Exception e) {  
  29.         e.printStackTrace();  
  30.     }  
  31. }