简体   繁体   中英

How to get a pdf into the java code from a url?

I have a java code which parses a PDF. But it loads the PDF locally. But I now want it to source the pdf from a url, say " https://www.abc.com/xyz.pdf " instead of "C:\\xyz.pdf", if I just change strings, it throws error.

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

Also, I get java.net.UnknownHostException when I try the above code at line 2. The link works fine in a browser.

In java if you want to read directly from URL, you can use 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();

Basically you have to use the URL.openstream method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM