java中write(byte[] b)與write(byte[] b,int off,int len)區別,bytelen
在項目中要上傳檔案或者圖片
private static final int BUFFER_SIZE = 16 * 1024;
private static void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream ut = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
ut = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
檔案上傳很簡單就實現了,可是突然我發現上傳的檔案都比原來大十幾K.由於系統使用者量很大,如果有一百萬張,那占的空間可非常大了,查看jdk文檔,其中在BufferedOutputStream文檔中有write(byte[] b, int off, int len)和write(byte[] b).其中write(byte[ ] b,int off,int len)注釋為:
將指定 byte 數組中從位移量off開始的len個位元組寫入此緩衝的輸出資料流。一般來說,此方法將給定數組的位元組存入此流的緩衝區中,根據需要將該緩衝區重新整理,並轉到底層輸出資料流。但是,如果請求的長度至少與此流的緩衝區大小相同,則此方法將重新整理該緩衝區並將各個位元組直接寫入底層輸出資料流。因此多餘的BufferedOutputStream將不必複製資料。
果然我試了write(byte[ ] b,int off,int len)方法檔案沒有變大.由於習慣,在跟蹤下去看看是究竟怎麼回事.最後發現write(byte[ ]) 是調用了write(byte[] b,int off,int len),其中len數組的長度.問題就出在這裡.在最後一次寫入流時,len一般不會為讀入位元組的長度.除非檔案大小剛好被BUFFER_SIZE整除.而通過 while ((len = in.read(buffer)) > 0){write(byte[] b,int off,int len) ,其中len為實際讀入流的位元組長度.所以這個方法不會增加檔案大小,不會把多餘的位元組寫進去.
也不知道為什麼sun在Java中增加了write(byte[] b) 方法,不過該方法不會影響檔案.當我用MagickImage處理一把,檔案就恢複原樣了.