[英]Java Buffered Stream Writer writes short and corrupts DOCX files
我正在編寫文件上傳Java應用程序,我的問題是我的緩沖編寫器正在寫的文件大小不足完整文件的大小。 當我記錄寫入的字節時,新文件大小與舊文件大小-始終存在差異-我的緩沖讀取器根據緩沖區大小而停止運行。
因此,例如,當我的緩沖區設置為1024時-它僅寫入1024的增量,而不寫入其余字節(小於1024字節的最后幾個字節)。 DOCX(所有X Office文件)對文件的大小很挑剔,當您將它們寫短時,它們在辦公室被標記為損壞。
int originalSize = (int) file.length();
FileInputStream fis = null;
BufferedOutputStream bout = null;
BufferedInputStream bin = null;
FileOutputStream fout = null;
try {
fis = new FileInputStream(file);
fout = new FileOutputStream(newfile);
bout = new BufferedOutputStream(fout);
bin = new BufferedInputStream(fis);
log.info("Setting buffer to 1024");
int total = 0;
byte buf[] = new byte[1024]; // Buffer Size (works when set to 1)
while((bin.read(buf)) != -1) {
Float size = (float) newfile.length();
bout.write(buf);
total += buf.length;
log.info("LOOP: Current Size:" + total + " New File Size: " + size + " Original Size: " + originalSize);
}
int size = (int) newfile.length();
log.info("new file size bytes: " + size);
log.info("original file size bytes: " + originalSize);
log.info("File created: " + newfile.getName());
return newfile.getName();
} catch (Exception e) {
log.error("ERROR: during input output file streaming: " + e.getMessage());
} finally {
fis.close();
bout.close();
bin.close();
}
所以這在我將“緩沖區大小”設置為1個字節時有效,因為它將完全寫出文件
關於如何獲得這樣的緩沖寫入器的任何建議(我必須對其進行緩沖/使用流,因為它可以處理大量文件)以為該文件寫出確切的字節數,對此將不勝感激。
謝謝
read()
方法返回讀取的字節數。 緩沖區並不總是完全填充。
您應該這樣寫:
int bytesRead = 0;
while((bytesRead = bin.read(buf)) != -1) {
bout.write(buf, 0, bytesRead); // Write only the bytes read
total += bytesRead;
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.