How to load a pdf file from a given url in java?

I want to make a Java application that loads a file from a URL at runtime. Is there any function I can use for this?

This piece of code worked only for the .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(); 
+8
java file pdf download
source share
1 answer

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

(these are simplified examples, you still need to handle exceptions and ensure that threads close yourself)

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

With Java 7, we can also use

 URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG"); InputStream in = url.openStream(); Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING); in.close(); 
+23
source share

All Articles