java实现下载网络资源至服务器
程序员文章站
2022-05-06 08:01:07
...
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @desc 文件工具类
* @com
* @Author tanzhiming(Jruoning) 2020/1/2 10:07
*/
@Slf4j
public class FileUtils extends FileUtil {
/**
* 下载网络文件至服务器本地
* @param urlStr 网络路径
* @param apPath 存储路径+文件名称
* @return
*/
public static void downloadFromUrl(String urlStr, String apPath) {
log.info("开始下载网络文件[{}]至服务器[{}].......", urlStr, apPath);
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = null;
try {
inputStream = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
//获取自己数组
byte[] getData = new byte[0];
try {
getData = readInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
File file = new File(apPath);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
FileUtils.mkdir(parentFile);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(getData);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("文件下载成功至服务器[{}]", apPath);
}
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
上一篇: 事件的循环绑定与委托
下一篇: Crazy Search(hash算法)