log4j-1.2.17.jar
slf4j-api-1.7.36.jar
slf4j-log4j12-1.7.7.jar
package com;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.text.DecimalFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private static final DecimalFormat format = new DecimalFormat("#.00");
public static void main(String[] args) {
// TODO 自动生成的方法存根
String url = "https://cos.cmhk.com/cos-download/v1/downloadFile/1/dmd-private-bucket/166c80c932710fb1168de9ead13f585d/%E5%95%86%E4%B8%9A%E7%99%BB%E8%AE%B0%E8%AF%81.pdf?expires=5000000000&signature=0101x5QX1VZY:RjIyOUQ2NjUxNzFFQjVBNUM5M0FCMzY4QUVFMEQ3Nzc5OUFBN0M3RQ==";
String resourceName = "商业登记证.pdf";
File file = new File("1.txt");
String pathString = file.getAbsolutePath().replace("1.txt", "") + "downloadFile\\" + resourceName;
downloadUsingURLConnection(url, pathString);
downloadUsingNIO(url, pathString);
downloadUsingStream(url, pathString);
}
/**
* 使用URLConnection getInputStream方法来创建输入流,然后使用文件输出流从输入流中读取数据并写入文件。
*
* @param urlStr 文件下载url
* @param filePath 文件本地保存位置
*/
public static void downloadUsingURLConnection(String urlStr, String filePath) {
URL url = null;
URLConnection con = null;
InputStream is = null;
FileOutputStream fos = null;
File file = new File(filePath);
try {
if (!file.exists()) {
if (!mkdirParents(file)) {
log.info("创建父级目录失败!");
return;
}
if(!file.createNewFile()){
log.info("创建文件: {} 失败!", filePath);
return;
}
}
log.info("需要下载文件的 URL 为:{}", urlStr);
url = new URL(urlStr);
con = url.openConnection();
// 设置是否向URLConnection输出
con.setDoInput(true);
// 设置是否从UrlConnection读入
con.setDoOutput(true);
//连接超时时间
con.setConnectTimeout(60 * 1000);
//反馈超时时间
con.setReadTimeout(60 * 1000);
log.info("建立连接..........");
// 建立连接
con.connect();
//获取流
is = con.getInputStream();
log.info("建立连接成功");
fos = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int count = 0;
log.info("开始下载.........");
while ((count = is.read(buffer, 0, 1024)) != -1) {
fos.write(buffer, 0, count);
}
log.info("下载文件成功!");
log.info("文件保存到:{}", filePath);
printObjectSize(file.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if (null != fos) {
fos.close();
}
if (null != is) {
is.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
/**
* 使用URL openStream方法来创建输入流,然后使用文件输出流从输入流中读取数据并写入文件。
*
* @param urlStr 文件下载url
* @param filePath 文件本地保存位置
*/
public static void downloadUsingStream(String urlStr, String filePath) {
URL url = null;
BufferedInputStream bis = null;
FileOutputStream fis = null;
File file = new File(filePath);
try {
if (!file.exists()) {
if (!mkdirParents(file)) {
log.info("创建父级目录失败!");
return;
}
if(!file.createNewFile()){
log.info("创建文件: {} 失败!", filePath);
return;
}
}
log.info("需要下载文件的 URL 为:{}", urlStr);
url = new URL(urlStr);
log.info("建立连接..........");
bis = new BufferedInputStream(url.openStream());
log.info("建立连接成功");
fis = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int count = 0;
log.info("开始下载.........");
while ((count = bis.read(buffer, 0, 1024)) != -1) {
fis.write(buffer, 0, count);
}
log.info("下载文件成功!");
log.info("文件保存到:{}", filePath);
printObjectSize(file.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if (null != fis) {
fis.close();
}
if (null != bis) {
bis.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
/**
* 从URL流数据创建字节通道,。然后使用文件输出流将其写入文件。
*
* @param urlStr 文件下载url
* @param filePath 文件本地保存位置
*/
public static void downloadUsingNIO(String urlStr, String filePath) {
URL url = null;
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
File file = new File(filePath);
try {
if (!file.exists()) {
if (!mkdirParents(file)) {
log.info("创建父级目录失败!");
return;
}
if(!file.createNewFile()){
log.info("创建文件: {} 失败!", filePath);
return;
}
}
log.info("需要下载文件的 URL 为:{}", urlStr);
url = new URL(urlStr);
log.info("建立连接..........");
rbc = Channels.newChannel(url.openStream());
log.info("建立连接成功");
fos = new FileOutputStream(filePath);
log.info("开始下载.........");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
log.info("下载文件成功!");
log.info("文件保存到:{}", filePath);
printObjectSize(file.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if (null != fos) {
fos.close();
}
if (null != rbc) {
rbc.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
/**
* 判断文件的父级目录是否存在,不存在则创建
* @param file 文件
* @return true 父级目录存在或创建父级目录成功, false创建父级目录失败
*/
private static boolean mkdirParents(File file){
if (!file.getParentFile().exists()) {
return file.getParentFile().mkdirs();
}
else {
return true;
}
}
/**
* 打印对象大小
* @param myValueSize 对象大小
*/
private static void printObjectSize(Long myValueSize){
if (myValueSize < 1024){
log.info("文件大小为:" + myValueSize + " B");
}
else if (calKb(myValueSize) < 1024){
log.info("文件大小为:" + format.format(calKb(myValueSize)) + " KB");
}
else if(calKb(calKb(myValueSize)) < 1024){
log.info("文件大小为:" + format.format(calKb(calKb(myValueSize))) + " MB");
}
else {
log.info("文件大小为:" + format.format(calKb(calKb(calKb(myValueSize)))) + " GB");
}
}
/**
* bytes 转成 kb
* @param val bytes
* @return kb
*/
private static double calKb(double val) {
return val / 1024.00;
}
}
log4j.rootLogger=info,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %-5p %-5L --- [%-5t] %-10c : %m %n