【问题标题】:How to download a PDF from a given URL in Java? [duplicate]如何从 Java 中的给定 URL 下载 PDF? [复制]
【发布时间】:2013-12-14 11:14:42
【问题描述】:

我想制作一个 Java 应用程序,该应用程序在执行时会从 URL 下载文件。有没有我可以使用的功能来做到这一点?

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

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();

【问题讨论】:

  • 不一样,因为我不想下载整个网站,而是下载它的文件!不过谢谢!
  • 是一样的。这个问题不是在问如何下载整个网站。

标签: java file pdf download


【解决方案1】:

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

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

(这是简化的示例,您仍然需要处理异常并确保在正确的位置关闭流)

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.copy 和try-with-resources 来自动关闭 InputStream(在这种情况下不必手动关闭流):

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
}

【讨论】:

猜你喜欢
  • 2012-10-19
  • 1970-01-01
  • 2021-12-20
  • 2019-12-16
  • 2017-08-13
  • 2014-11-14
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多