此篇博客为从服务器下载zip文件然后保存到本地的记录;
1,文件下载步骤:
(1)通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)。
(2)通过HttpURLConnection设置请求参数,并发送请求,然后获取一个返 回的输入流。
(3)建立存储的目录以及保存的文件名。
(4)建立输出流并写入数据。
(5)关闭输入流和输出流。
2,代码实现:
public class HttpConnectionUtil {
private static Logger logger = Logger.getLogger(HttpConnectionUtil.class);
/**
* @param urlPath 下载路径
* @param fileSavePath 下载存放目录,包含文件名
* @return 返回下载文件
* @throws Exception
*/
public static File downloadFile(String urlPath, String fileSavePath) throws Exception {
logger.info("进入下载文件工具类");
File file = null;
BufferedInputStream bin = null;
OutputStream out = null;
HttpURLConnection httpURLConnection = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
httpURLConnection = (HttpURLConnection) urlConnection;
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 文件名
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
fileFullName = fileFullName.substring(fileFullName.lastIndexOf("/") + 1);
logger.info("开始下载文件:" + fileFullName);
logger.info("file length---->" + fileLength);
url.openConnection();
// 获取返回的输入流
bin = new BufferedInputStream(httpURLConnection.getInputStream());
file = new File(fileSavePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
out = new FileOutputStream(file);
int size = 0;
//int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
// len += size;
out.write(buf, 0, size);
// 打印下载百分比
// if ((len * 100 / fileLength)>50&&(len * 100 / fileLength)<55) {
// logger.info("下载了-------> " + len * 100 / fileLength + "%");
// }else if ((len * 100 / fileLength)>=98) {
// logger.info("下载了-------> " + len * 100 / fileLength + "%");
}
//logger.info("下载了-------> " + len * 100 / fileLength + "%");
}
return file;
} catch (Exception e) {
// TODO Auto-generated catch block
throw new CustomException(e.toString()+"文件下载异常,请检查下载链接$$"+urlPath);
} finally {
if (bin != null)
bin.close();
if (out != null)
out.close();
if (httpURLConnection != null)
httpURLConnection.close();
}
logger.info("下载文件结束:" + fileSavePath);
}
}
// 主方法
public static void main(String[] args){
String zipUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.zip";
String fileName = zipUrl.substring(zipUrl.lastIndexOf("/"));
//System.out.println("fileName---->"+fileName);
String filePath = "D:\\";
File file = downloadFile(zipUrl , filePath + fileName);
System.out.println("Run ok! file " + file);
}
引用自:https://www.cnblogs.com/RivenLw/p/10477458.html