如何在Java中从给定的URL下载PDF?

19

我想制作一个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();

2
不同了,因为我不想下载整个网站,只想下载其中的一个文件!谢谢! - JmRag
一样的。那个问题并不是在询问如何下载整个网站。 - Robin Green
1个回答

37

不要使用读取器和写入器,因为它们设计用于处理原始文本文件,而 PDF 不是这样的文件(因为它还包含许多其他信息,例如有关字体甚至图像的信息)。而是使用流来复制所有 原始字节

因此,使用 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.copytry-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
}

你是不是想在 while 循环的参数中使用赋值运算符? - louie mcconnell
@louiemcconnell 是的。 这个逻辑与http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html中的第一个例子相同,但是我正在读取字节,而不是行。 - Pshemo
我只有调用in.readAllBytes()并返回byteArray才成功了,但我不想让后端下载文件。 - André Luís Oliveira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接