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

查看:849
本文介绍了如何从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 file:

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


推荐答案

您可以使用 URL 类。然后只需从其InputStream读取并写入您在文件中读取的数据。

You can open connection using URL class. Then just read from its InputStream and write data you read in 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我们也可以使用

Since Java 7 we can also use

URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG");
InputStream in = url.openStream();
Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING);
in.close();

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

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