一、需求说明
在某接口中,第三方调用过程需要获取文件进行存储处理,而第三方不能直接通过上传方式上传文件,因此采用通过链接下载方式获取文件。
二、实现需求
采用java.net.URL类实现下载,实现前提是第三方调用接口过程传递的链接需有效。
具体代码如下:
//file_url-文件下载链接
public void DownloadByUrl(String file_url){
logger.info("下载路径:"+file_url);
String res = "ERR";
int bytesum = 0;
int byteread = 0;
try {
//文件存储地址
String path = "/usr/mydata/elastic/uploadfiles/";
URL url = new URL(file_url);
File uploadDir = new File(path);
//验证存储路径是否存在,不存在则自动创建文件夹
if ( !uploadDir.exists()){ uploadDir.mkdirs(); }
//采用时间戳对下载文件命名
String timeStr =new Date().getTime()+"";
String newFileName =timeStr+"u";
//通过路径获取文件后缀
String extName = ToolUtil.getFileExtension(file_url);
String saveUrl = path + newFileName+"."+extName;
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(saveUrl);
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
fs.close();
inStream.close();
res = saveUrl;
logger.info("下载完成了!");
} catch (MalformedURLException e) {
logger.info("下载异常1:"+e);
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
logger.info("下载异常2:"+e);
throw new RuntimeException(e);
} catch (IOException e) {
logger.info("下载异常3:"+e);
throw new RuntimeException(e);
}
}
注意事项:
(1)、本例正常执行前提是保持网络稳定;
(2)、本例执行过程请确保你的程序有足够的权限来读取网络连接和写入到指定的目录中;
(3)、本例对部分可能出现的异常没有做处理,例如网络连接中断、文件不存在、磁盘空间不足等。需完善错误处理和异常处理,保持代码健康运行。