Pshemo..
29
不要在这里使用读者和作者,因为它们旨在处理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开始我们也可以使用
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
}