ดาวน์โหลดไฟล์ด้วยเซิร์ฟเล็ต Tomcat ดาวน์โหลดไฟล์ไม่สมบูรณ์

ฉันมีเซิร์ฟเล็ตที่ดาวน์โหลดไฟล์ไปยังไคลเอนต์ที่ร้องขอ ตอนนี้เมื่อผู้ใช้ร้องขอดาวน์โหลดไฟล์ xml มันจะเริ่มดาวน์โหลดและเมื่อเสร็จแล้วไฟล์จะดูไม่สมบูรณ์ ข้อมูลบางส่วนหายไปที่ส่วนท้ายของไฟล์

รหัสของฉันดูเหมือนว่า:

File file = new File(location);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=" + fileName);

FileInputStream fileIn = new FileInputStream(file);
OutputStream out = response.getOutputStream();

byte[] outputByte = new byte[4096];
int length = -1;

//copy binary contect to output stream
while((length = fileIn.read(outputByte)) > 0)
{
    out.write(outputByte);
}

fileIn.close();
out.flush();
out.close();

รหัสของฉันดาวน์โหลดไฟล์ xml แบบเต็มไม่ได้อยู่ที่ไหน


person JimmyD    schedule 28.06.2017    source แหล่งที่มา


คำตอบ (1)


เปลี่ยน while loop ของคุณแบบนี้ ขนาดบัฟเฟอร์คือ 4096 คุณควรใช้เฉพาะความยาวที่อ่านใน read() ก่อนหน้าเท่านั้น

  //copy binary contect to output stream
  while((length = fileIn.read(outputByte)) > 0)
  {
     fileOut.write(outputByte, 0, length);
  }

อย่างไรก็ตาม คุณควรใช้ Guava ByteStreams สำหรับสิ่งนี้ คุณสามารถค้นหาห้องสมุดอื่น ๆ ที่รองรับสิ่งนี้ได้เช่นกัน

person Ramesh PVK    schedule 28.06.2017
comment
คุณช่วยอธิบายหน่อยได้ไหมว่าทำไมเราต้องใช้ write(byte[] b, int off, int len) แทน write(byte[] b) ใน เอกสาร java มีการกล่าวถึงว่าสัญญาทั่วไปสำหรับ write(b) คือมันควรจะมีผลเหมือนกับการเรียก write(b, 0, b.length) ทุกประการ - person Bharat; 11.12.2018
comment
ใช่ทั้งสองเหมือนกัน - person Ramesh PVK; 25.01.2019