Download file from URL in Java using java.io & java.nio
7 years ago Lalit Bhagtani 1
Download file from URL in Java :-
In this tutorial, we will learn to download file from URL in java. There are two different API’s in Java, which can be used for this purpose, java.io & java.nio. Let’s see an implementation using both API’s with the help of an example :-
Java IO :-
In case of Java IO, we will use URL and BufferedInputStream Object to read the data from the URL and FileOutputStream Object to write the data in the file.
Example :-
import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public class DownloadFileFromInternet { public static void main(String[] args){ String url = "https://codedestine.com/text.html"; String file = "C://file.txt"; BufferedInputStream bufferedIS = null; FileOutputStream fileOS = null; try { URL urlObj = new URL(url); bufferedIS = new BufferedInputStream(urlObj.openStream()); fileOS = new FileOutputStream(file); int data = bufferedIS.read(); while(data != -1){ fileOS.write(data); data = bufferedIS.read(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(fileOS != null){ fileOS.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(bufferedIS != null){ bufferedIS.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
Java NIO :-
In case of Java NIO, we will use URL and ReadableByteChannel Object to read the data from the URL and FileOutputStream Object to write the data in the file.
Example :-
import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class DownloadFileFromURL { public static void main(String[] args){ String url = "https://codedestine.com/text.html"; String file = "C://file.txt"; ReadableByteChannel readableBC = null; FileOutputStream fileOS = null; try { URL urlObj = new URL(url); readableBC = Channels.newChannel(urlObj.openStream()); fileOS = new FileOutputStream(file); fileOS.getChannel().transferFrom(readableBC, 0, Long.MAX_VALUE); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(fileOS != null){ fileOS.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(readableBC != null){ readableBC.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
You may also like :-
References :-
That’s all for Download file from URL in Java, If you liked it, please share your thoughts in comments section and share it with others too.
1 thought on “Download file from URL in Java using java.io & java.nio”
How can I download video from any given URL.