如何从 Java 中的给定 URL 下载 PDF?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20265740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to download a PDF from a given URL in Java?
提问by JmRag
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?
我想制作一个 Java 应用程序,该应用程序在执行时从 URL 下载文件。我可以使用任何功能来执行此操作吗?
This piece of code worked only for a .txt
file:
这段代码仅适用于一个.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();
采纳答案by Pshemo
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.
不要在此处使用 Readers 和 Writers,因为它们旨在处理 PDF 所没有的原始文本文件(因为它还包含许多其他信息,例如有关字体的信息,甚至图像)。而是使用 Streams 来复制所有原始字节。
So open connection using URL
class. Then just read from its InputStream and write raw bytes to your file.
所以使用URL
类打开连接。然后只需从它的 InputStream 读取并将原始字节写入您的文件。
(this is simplified example, you still need to handle exceptions and ensure closing streams in right places)
(这是简化示例,您仍然需要处理异常并确保在正确的位置关闭流)
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");
Since Java 7 we can also use Files.copy
and the try-with-resourcesto automatically close the InputStream (the stream doesn't have to be closed manually in this case):
由于Java 7中,我们还可以使用Files.copy
与尝试,与资源自动关闭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
}