JmR*_*Rag 14 java pdf file download
我想创建一个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();
Run Code Online (Sandbox Code Playgroud)
Psh*_*emo 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");
Run Code Online (Sandbox Code Playgroud)
从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
}
Run Code Online (Sandbox Code Playgroud)