本文主要是介绍java实现下载网络资源至服务器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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();}
}
这篇关于java实现下载网络资源至服务器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!