close fd 死循环_inputStream.read(byte[] )死循环、阻塞问题

文件下载代码如下:

public static String download(String fileUrl, String folderPath) {

URL url;

HttpURLConnection conn = null;

FileOutputStream outputStream = null;

BufferedInputStream inputStream = null;

try {

url = new URL(fileUrl);

conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(10 * 1000);

conn.setReadTimeout(20 * 1000);

String subPrefix=fileUrl.substring(fileUrl.lastIndexOf("/")+1);

File file = new File(folderPath + File.separator+subPrefix);

outputStream = new FileOutputStream(file);

inputStream = new BufferedInputStream(conn.getInputStream());

byte[] buf = new byte[1024];

int size = 0;

while ((size = inputStream.read(buf)) != -1) {

outputStream.write(buf, 0, size);

}

return subPrefix;

} catch (Exception e) {

e.printStackTrace();

logger.error("oss文件下载失败:",e);

} finally {

try {

if (outputStream != null) {

outputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}

try {

if (inputStream != null) {

inputStream.close();

}

} catch (IOException e) {

e.printStackTrace();

}

if (conn != null) {

conn.disconnect();

}

}

return null;

}

该段代码一直很健壮,今天发现有一个文件进入下载之后,一直没有出该方法是(看起来很想进入到while中一直死循环了),根据日志(代码中没贴出日志代码),并查找相关资料,推测原因是由于inputStream.read(buf))这段代码一直阻塞造成的,该问题的复现很难,因为我在本机、下载了同样的文件100多次,都没有出现,后来程序逻辑进行简单修改(先获取文件大小,然后下载到与文件文件大小相等的时候,就退出循环)

int fileLength = conn.getContentLength();   //最大值2147483647  约2Gb

int downloadLength = 0;

然后在

while ((size = inputStream.read(buf)) != -1) {

downloadLength += size;

outputStream.write(buf, 0, size);

if(fileLength == downloadLength){//防止最后一次读取的时候,一直阻塞

break;

}

}

后记:

经过两三个月的 验证,程序再无下载文件的时候卡死现象,一直运行良好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值