java http下载文件。在activemq blobmessage 的blob对象读时用到。

本文针对使用Java进行文件下载过程中出现的问题,提供了有效的解决方案。主要介绍了如何正确地以二进制方式处理输入流,避免一次性将整个对象加载到内存中,并优化了读写操作以提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://stackoverflow.com/questions/401748/corrupt-file-when-using-java-to-download-file

 

 

错误代码
URL targetUrl = new URL(urlForFile);
InputStream content = (InputStream)targetUrl.getContent();
BufferedInputStream buffered = new BufferedInputStream(content);
File savedFile = File.createTempFile("temp",".dat");

FileOutputStream fos = new FileOutputStream(savedFile);
int letter;
while((letter = buffered.read()) != -1)
fos.write(letter);
fos.close();

 

 

三大问题:

  1. You're not just treating the input as bytes,未彻底二进制处理
  2. You're needlessly pulling the entire object into memory at once,性能考虑
  3. You're doing multiple method calls for every single byte read and written -- use the array based read/write!,性能考虑

Here's a redo,经过验证的正确处理图片的代码。:

URL targetUrl = new URL(urlForFile); 
InputStream is = targetUrl.getInputStream(); 
File savedFile = File.createTempFile("temp",".dat"); 
FileOutputStream fos = new FileOutputStream(savedFile); 
 
int count; 
byte[] buff = new byte[16 * 1024]; 
while((count = is.read(buff)) != -1) { 
    fos.write(buff, 0, count); 
} 
fos.close(); 
content.close(); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值