raka
raka

Reputation: 365

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.

Upvotes: 1

Views: 4993

Answers (1)

user3309301
user3309301

Reputation: 301

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

Upvotes: 2

Related Questions