文件下载代码如下:
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;
}
}
后记:
经过两三个月的 验证,程序再无下载文件的时候卡死现象,一直运行良好