如何从 Java 中的给定 URL 下载 PDF? [英] How to download a PDF from a given URL in Java?

查看:26
本文介绍了如何从 Java 中的给定 URL 下载 PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个 Java 应用程序,该应用程序在执行时从 URL 下载文件.我可以使用任何函数来执行此操作吗?

I want to make a Java application that when executed downloads a file from a URL. Is there any function that I can use in order to do this?

这段代码仅适用于 .txt 文件:

This piece of code worked only for a .txt file:

URL url= new URL("http://cgi.di.uoa.gr/~std10108/a.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
PrintWriter writer = new PrintWriter("file.txt", "UTF-8");

String inputLine;
while ((inputLine = in.readLine()) != null){
   writer.write(inputLine+ System.getProperty( "line.separator" ));               
   System.out.println(inputLine);
}
writer.close();
in.close();

推荐答案

不要在此处使用 Readers 和 Writers,因为它们旨在处理 PDF 不具备的原始文本文件(因为它还包含许多其他信息,例如有关字体,甚至图像).而是使用 Streams 复制所有原始字节.

Don't use Readers and Writers here as they are designed to handle raw-text files which PDF is not (since it also contains many other information like info about font, and even images). Instead use Streams to copy all raw bytes.

所以使用 URL 类打开连接.然后只需从它的 InputStream 读取并将原始字节写入您的文件.

So open connection using URL class. Then just read from its InputStream and write raw bytes to your file.

(这是一个简化的例子,你仍然需要处理异常并确保在正确的地方关闭流)

System.out.println("opening connection");
URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File("yourFile.jpg"));

System.out.println("reading from resource and writing to file...");
int length = -1;
byte[] buffer = new byte[1024];// buffer for portion of data from connection
while ((length = in.read(buffer)) > -1) {
    fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File downloaded");

从 Java 7 开始,我们还可以使用 Files.copytry-with-resources 自动关闭 InputStream(在这种情况下不必手动关闭流):

Since Java 7 we can also use Files.copy and the try-with-resources to automatically close the InputStream (the stream doesn't have to be closed manually in this case):

URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG");
try (InputStream in = url.openStream()) {
   Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
   // handle exception
}

这篇关于如何从 Java 中的给定 URL 下载 PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆