java 完美讀取位元組流 例項
阿新 • • 發佈:2019-01-31
在使用BufferedInputStream讀取位元組流是,若最後剩餘的位元組數,小於指定讀取的位元組數,則返回的位元組陣列的內容長度仍然是指定的位元組數,這時若寫入新的檔案,或者寫
入socket時,則會出現目標檔案比原檔案多幾個位元組,並不是和原檔案一模一樣的大小。下面的例子可以完美的解決這個問題。^_^
- @Override
- publicvoid run() {
- try {
- FileInputStream fis = null;
- BufferedInputStream bis = null;
-
fis = new
- if (fis != null) {
- bis = new BufferedInputStream(fis);
- }
- if (bis != null) {
- byte[] bs = newbyte[512];
- while(bis.available() > 512) {
- bis.read(bs);
-
ByteBuffer src = ByteBuffer.wrap(bs);
- // write data to client socket channel
- lsockChannel.write(src);
- Arrays.fill(bs, (byte)0);
- }
- // 處理不足512的剩餘部分
- int remain = bis.available();
- byte[] last = newbyte[remain];
-
bis.read(last);
- lsockChannel.write(ByteBuffer.wrap(last));
- bis.close();
- fis.close();
- lsockChannel.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }