java下载pdf_java程序下载pdf文件

该博客展示了如何使用Java的HttpURLConnection类从指定URL下载PDF文件。通过创建URL对象,打开连接,设置超时,读取并写入文件内容到本地文件系统,实现了文件的下载。
摘要由CSDN通过智能技术生成

展开全部

主要是 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) {

62616964757a686964616fe58685e5aeb931333337623536new 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 不存在或者连接超时");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值