我有一个解析 PDF 的 java 代码。但它会在本地加载 PDF。但我现在希望它从 URL 获取 pdf,比如“https://www.abc.com/xyz.pdf”而不是“C:\xyz.pdf”,如果我只是更改字符串,它会抛出错误。
URL URL = new URL("https://www.abc.com/xyz.pdf");
InputStream in = URL.openStream();
FileOutputStream fos = new FileOutputStream(new File(temp.pdf));
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();
此外,当我在第 2 行尝试上述代码时,我得到了 java.net.UnknownHostException。该链接在浏览器中工作正常。
最佳答案
在java中如果想直接从URL读取,可以使用 this :
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
基本上你必须使用 URL.openstream 方法
关于java - 如何从url获取pdf到java代码中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24445231/