java程序下载pdf文件
知道外网pdf文件的路径http://211.103.156.163/u/cms/www/201511/25051940i6ou.pdf需要将该文件下载到本地。求大神帮忙...
知道外网pdf文件的路径http://211.103.156.163/u/cms/www/201511/25051940i6ou.pdf 需要将该文件下载到本地。求大神帮忙写个程序
展开
1个回答
展开全部
主要是 URL 和 HttpURLConnection 类的运用,看代码:
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDownloader {
private static final String REMOTE_FILE_URL = "http://211.103.156.163/u/cms/www/201511/25051940i6ou.pdf";
private static final String LOCAL_FILE_PATH = "D:/some.pdf"; // 改成你保存 文件的路径
public static void main(String[] args) {
new HttpDownloader(REMOTE_FILE_URL, LOCAL_FILE_PATH).download();
}
private String remoteFileUrl;
private String localFilePath;
public HttpDownloader(String remoteFileUrl, String localFilePath) {
this.remoteFileUrl = remoteFileUrl;
this.localFilePath = localFilePath;
}
public void download() {
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 不存在或者连接超时");
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询