下载第三方.pdf文件,只需提供第三方下载地址即可
package cn.itcast;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDownload {
private static final String REMOTE_FILE_URL = "http://211.103.156.163/201811/25051940i6ou.pdf";
private static final String LOCAL_FILE_PATH = "D:/picture.pdf"; // 改成你保存 文件的路径 文件类型自己选择.pdf url需要替换
public static void main(String[] args) {
download(REMOTE_FILE_URL, LOCAL_FILE_PATH);
}
/* 注释说明
* try(resouces){
* 代码区
} catch (Exception e){
异常处理
}
// 这里的resource会自动关闭,无需在手动关闭流
// 1. resource 必须继承自 java.lang.AutoCloseable
// 2. 定义和赋值必须都在try里完成
*/
private static void download(String remoteFileUrl, String localFilePath) {
try {
URL url = new URL(remoteFileUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5 * 1000); // 5000 毫秒内没有连接上 则放弃连接
httpURLConnection.connect(); // 连接
System.out.println("连接 URL 成功~");
int fileLenght = httpURLConnection.getContentLength();
System.out.println("文件大小:" + (fileLenght / 1024.0) + " KB");
System.out.println("开始下载...");
try (DataInputStream dis = new DataInputStream(httpURLConnection.getInputStream());
FileOutputStream fos = new FileOutputStream(localFilePath)) {
byte[] buf = new byte[10240]; // 根据实际情况可以 增大 buf 大小
for (int readSize; (readSize = dis.read(buf)) > 0;) {
fos.write(buf, 0, readSize);
}
System.out.println("下载完毕~");
} catch (IOException ex) {
System.out.println("下载时出错");
}
httpURLConnection.disconnect();
} catch (IOException ex) {
System.out.println("URL 不存在或者连接超时");
}
}
}
上传至FastDFs服务器
待续。。。。。