看板 java 關於我們 聯絡資訊
剛剛在找資料的時候瞄到一篇blog文章,閱後大驚,轉錄一下 ------------------------------------------------------ 這麼多年了,我一直使用下列的程式碼在處理java 搬檔問題 fis = new FileInputStream(file); fos = new FileOutputStream(file1); byte fileBuffer[] = new byte[512]; int fileIdx = -1; while ((fileIdx = fis.read(fileBuffer)) != -1) { fos.write(fileBuffer); } 有時會發生excel檔或是pdf檔上傳後不能開啟, 後來發現用fos.write(fileBuffer,0,fileIdx);這個方法是可以解決的, 應該就是只寫入這次截取的長度,而不是寫入buffer的長度. ------------------------------------------------------ 出處就不附了(反正隨便google也找的到),免得搞成我好像故意在鞭他一樣... 我大驚的原因是怎會有一個多年經驗的程式設計師會犯這種錯,實在很誇張呀!! 況且,如果照他文內所述是"搬檔",也不是用這個方法呀...XD 不過後來看到這段 code, from http://caterpillar.onlyfun.net/Gossip/JavaGossip-V2/FileInOutStream.htm ------------------------------------------------------ byte[] buffer = new byte[1024]; FileInputStream fileInputStream = new FileInputStream(new File(args[0])); FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1])); System.out.println("複製檔案:" + fileInputStream.available() + "位元組"); while(true) { // 從來源檔案讀取資料至緩衝區 int length = fileInputStream.read(buffer); if(length == buffer.length) { // 將陣列資料寫入目的檔案 fileOutputStream.write(buffer); } else { byte[] buf = new byte[length]; System.arraycopy(buffer, 0, buf, 0, length); fileOutputStream.write(buf); break; } } // 關閉串流 fileInputStream.close(); fileOutputStream.close(); System.out.println("複製完成"); ------------------------------------------------------ 就覺得 OutputStream 的 write(byte[] b, int off, int len) 好可憐, 好像真的很討人厭,都沒有人愛用它...XD 為什麼要搞出這種脫褲子放屁的行為呢? 真難理解... 而且 InputStream available() 的原意應該不是這樣用的,只是恰巧在 讀取檔案時,剛好等於檔案大小而已。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.32
GALINE:當api太多時,很容易難以看清全貌…吧 09/18 00:39
JustinHere:學藝不精,感謝指正。。。Orz.... 09/18 14:42
slalala:感謝原PO解決我去年在"搬運" *.mdb檔案時出錯的困惑Orz 10/11 00:27