19

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 .txt file:

URL url= new URL("http://cgi.di.uoa.gr/~std10108/a.txt"); 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" )); System.out.println(inputLine); } writer.close(); in.close(); 
2
  • 2
    It's not the same since I don't want to donwload a whole site but a file of it! Thanks though! Commented Nov 28, 2013 at 16:27
  • It is the same. That question is NOT asking about how to download a whole site. Commented Nov 17, 2018 at 6:24

1 Answer 1

37

Don't use Readers and Writers here as they are designed to handle raw-text files which PDF is not (since it also contains many other information like info about font, and even images). Instead use Streams to copy all raw bytes.

So open connection using URL class. Then just read from its InputStream and write raw bytes to your file.

(this is simplified example, you still need to handle exceptions and ensure closing streams in right places)

System.out.println("opening connection"); URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG"); 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 = in.read(buffer)) > -1) { fos.write(buffer, 0, length); } fos.close(); in.close(); System.out.println("File downloaded"); 

Since Java 7 we can also use Files.copy and the try-with-resources to automatically close the InputStream (the stream doesn't have to be closed manually in this case):

URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG"); try (InputStream in = url.openStream()) { Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { // handle exception } 
Sign up to request clarification or add additional context in comments.

3 Comments

Did you mean to use the assignment operator as the parameter of the while loop?
@louiemcconnell Yes. This logic is same as in first example from: docs.oracle.com/javase/tutorial/networking/urls/… but instead of reading lines I am reading bytes.
I got success only calling in.readAllBytes() and returning the byteArray but I didn't want the backend to download the file

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.