JmRag JmRag - 1 year ago 121
Java Question

How to download a PDF from a given URL in Java?

I want to make a Java application that when executed downloads a file from a URL. Is there any function that I can use in order to do this?

This piece of code worked only for a


URL url= new URL("");
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" ));

Answer Source

You can open connection using URL class. Then just read from its InputStream and write data you read in your file.

(this are simplified examples, you still need to handle exceptions and ensure closing streams on your own)

System.out.println("opening connection");
URL url = new URL("");
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 = > -1) {
    fos.write(buffer, 0, length);
System.out.println("File downloaded");

Since Java 7 we can also use

URL url = new URL("");
InputStream in = url.openStream();
Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download