如何使用Java流从Web获取PDF文件 [英] How to get PDF file from web using java streams
本文介绍了如何使用Java流从Web获取PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从网上下载PDF文件,例如http://www.math.uni-goettingen.de/zirkel/loesungen/blatt15/loes15.pdf
此链接.我必须使用Streams做到这一点.有了图片,它对我来说效果很好:
I need to download PDF file from web, for example http://www.math.uni-goettingen.de/zirkel/loesungen/blatt15/loes15.pdf
this link. I have to do it using Streams. With images it works fine by me :
public static void main(String[] args) {
try {
//get the url page from the arguments array
String arg = args[0];
URL url = new URL("https://cs7065.vk.me/c637923/v637923205/25608/AD8WhOSx1ic.jpg");
try{
//jpg
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("borrowed_image.jpg");
fos.write(response);
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
但是使用PDf则不起作用.可能是什么问题?
But with PDf it does not work. What could be the problem ?
推荐答案
我对您的代码进行了较小的编辑,以修复语法错误,这似乎可行(如下).考虑将close()
语句放在finally
块中.
I made minor edits to your code to fix syntax errors and, this seems to work (below). Consider placing your close()
statements in a finally
block.
package org.snb;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class PdfTester {
public static void main(String[] args) {
//get the url page from the arguments array
try{
//String arg = args[0];
URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
//jpg
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("/tmp/bart.pdf");
fos.write(response);
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
这篇关于如何使用Java流从Web获取PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文