How To Download A File In Java

In Coffee how to download files from any given URL? This tutorial works if you have any of below questions:
- Download a file from a URL in Coffee.
- How to Download a File from a URL in Coffee
- How to download and salvage a file from Internet using Java
- java download file from url Code Instance
In that location are 5 different ways yous could download files from whatsoever given URL in Java.
- File Download using apache commons-io. Single line of code.
- File Download using Stream Operation
- File Download using NIO Operation
- File Download using Files.copy()
- File Download using Apache HttpComponents()
Create java class: CrunchifyDownloadFileFromURL.java
bundle crunchify.com.tutorial; import org.apache.eatables.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.customer.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.*; import java.internet.URI; import java.cyberspace.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import coffee.nio.file.Files; import java.nio.file.Paths; import coffee.nio.file.StandardCopyOption; /** * @author Crunchify.com * <p> * In Java How to Download file from any given URL? * <p> * v different ways: * 1. File Download using apache commons-io. Just line of lawmaking * two. File Download using Stream Operation * three. File Download using NIO Performance * 4. File Download using Files.copy() * 5. File Download using Apache HttpComponents() */ public form CrunchifyDownloadFileFromURL { public static void main(String[] args) { String crunchifyRobotsURL = "https://crunchify.com/robots.txt"; try { // Method-1: File Download using apache commons-io. Only line of code. crunchifyFileDownloadUsingApacheCommonsIO(crunchifyRobotsURL, "/Users/app/Download/robots_commons_io.txt"); // Method-2: File Download using Stream Operation crunchifyFileDownloadUsingStream(crunchifyRobotsURL, "/Users/app/Download/robots_stream.txt"); // Method-3: File Download using NIO Operation crunchifyFileDownloadUsingNIO(crunchifyRobotsURL, "/Users/app/Download/robots_nio.txt"); // Method-4: File Download using Files.re-create() crunchifyFileDownloadUsingFilesCopy(crunchifyRobotsURL, "/Users/app/Download/robots_files_copy.txt"); // Method-five: File Download using Apache HttpComponents() crunchifyFileDownloadUsingHttpComponents(crunchifyRobotsURL, "/Users/app/Download/robots_httpcomponents.txt"); } catch (IOException crunchifyException) { crunchifyException.printStackTrace(); } } // Method-i: Using apache commons-io. But single line of code. // FileUtils.copyURLToFile(URL, File); private static void crunchifyFileDownloadUsingApacheCommonsIO(String crunchifyURL, String crunchifyFileLocalPath) { URL crunchifyRobotsURL = nada; try { crunchifyRobotsURL = new URL(crunchifyURL); FileUtils.copyURLToFile(crunchifyRobotsURL, new File(crunchifyFileLocalPath)); } grab (IOException e) { e.printStackTrace(); } printResult("File Downloaded Successfully with apache commons-io Operation \due north"); } // Method-2: File Download using Stream Operation private static void crunchifyFileDownloadUsingStream(String crunchifyURL, String crunchifyFileLocalPath) throws IOException { URL crunchifyRobotsURL = new URL(crunchifyURL); // BufferedInputStream(): Creates a BufferedInputStream and saves its argument, the input stream in, for later use. An internal buffer array is created and stored in buf. BufferedInputStream crunchifyInputStream = new BufferedInputStream(crunchifyRobotsURL.openStream()); FileOutputStream crunchifyOutputStream = new FileOutputStream(crunchifyFileLocalPath); byte[] crunchifySpace = new byte[2048]; int crunchifyCounter = 0; while ((crunchifyCounter = crunchifyInputStream.read(crunchifySpace, 0, 1024)) != -1) { crunchifyOutputStream.write(crunchifySpace, 0, crunchifyCounter); } crunchifyOutputStream.close(); crunchifyInputStream.close(); printResult("File Downloaded Successfully with Java Stream Functioning \north"); } // Method-3: File Download using NIO Operation private static void crunchifyFileDownloadUsingNIO(String crunchifyURL, String crunchifyFileLocalPath) throws IOException { URL crunchifyRobotsURL = new URL(crunchifyURL); // ReadableByteChannel(): A aqueduct that tin can read bytes. Only one read operation upon a readable aqueduct may be in progress at any given time. If one thread initiates a read performance upon a channel then any other thread that attempts to initiate another read operation will block until the kickoff operation is complete. // Whether or not other kinds of I/O operations may proceed concurrently with a read functioning depends upon the type of the channel. // openStream(): Opens a connexion to this URL and returns an InputStream for reading from that connection. ReadableByteChannel crunchifyByteChannel = Channels.newChannel(crunchifyRobotsURL.openStream()); // FileOutputStream(): A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, permit a file to be opened for writing by merely 1 FileOutputStream (or other file-writing object) at a fourth dimension. // In such situations the constructors in this class will neglect if the file involved is already open up. FileOutputStream crunchifyOutputStream = new FileOutputStream(crunchifyFileLocalPath); // getChannel(): Returns the unique FileChannel object associated with this file output stream. // transferFrom(): Transfers bytes into this aqueduct's file from the given readable byte aqueduct. // An attempt is made to read up to count bytes from the source aqueduct and write them to this channel's file starting at the given position. An invocation of this method may or may not transfer all of the requested bytes; whether or not it does then depends upon the natures and states of the channels. // Fewer than the requested number of bytes will be transferred if the source channel has fewer than count bytes remaining, or if the source aqueduct is non-blocking and has fewer than count bytes immediately available in its input buffer. crunchifyOutputStream.getChannel().transferFrom(crunchifyByteChannel, 0, Long.MAX_VALUE); // A constant holding the maximum value a long can have. // Closes this file output stream and releases any organization resources associated with this stream. This file output stream may no longer be used for writing bytes. crunchifyOutputStream.close(); // Closes this aqueduct. After a aqueduct is closed, whatever further attempt to invoke I/O operations upon it will crusade a ClosedChannelException to exist thrown. crunchifyByteChannel.shut(); printResult("File Downloaded Successfully with Java NIO ReadableByteChannel Operation \n"); } // Method-4: File Download using Files.copy() private static void crunchifyFileDownloadUsingFilesCopy(String crunchifyURL, String crunchifyFileLocalPath) { // URI Creates a URI by parsing the given cord. // This convenience manufactory method works as if by invoking the URI(String) constructor; // any URISyntaxException thrown by the constructor is caught and wrapped in a new IllegalArgumentException object, which is then thrown. endeavor (InputStream crunchifyInputStream = URI.create(crunchifyURL).toURL().openStream()) { // Files: This class consists exclusively of static methods that operate on files, directories, or other types of files. // copy() Copies all bytes from an input stream to a file. On render, the input stream will exist at end of stream. // Paths: This class consists exclusively of static methods that render a Path by converting a path string or URI. // Paths.get() Converts a path cord, or a sequence of strings that when joined grade a path string, to a Path. Files.copy(crunchifyInputStream, Paths.get(crunchifyFileLocalPath), StandardCopyOption.REPLACE_EXISTING); } catch (IOException eastward) { // printStackTrace: Prints this throwable and its backtrace to the standard error stream. east.printStackTrace(); } printResult("File Downloaded Successfully with Files.re-create() Functioning \n"); } // Method-five: File Download using Apache HttpComponents() individual static void crunchifyFileDownloadUsingHttpComponents(String crunchifyURL, String crunchifyFileLocalPath) { CloseableHttpClient crunchifyHTTPClient = HttpClients.createDefault(); HttpGet crunchifyHTTPGet = new HttpGet(crunchifyURL); CloseableHttpResponse crunchifyHTTPResponse = null; try { crunchifyHTTPResponse = crunchifyHTTPClient.execute(crunchifyHTTPGet); HttpEntity crunchifyHttpEntity = crunchifyHTTPResponse.getEntity(); if (crunchifyHttpEntity != zilch) { FileUtils.copyInputStreamToFile(crunchifyHttpEntity.getContent(), new File(crunchifyFileLocalPath)); } } catch (IOException east) { // IOException: Signals that an I/O exception of some sort has occurred. // This class is the general class of exceptions produced by failed or interrupted I/O operations. e.printStackTrace(); } printResult("File Downloaded Successfully with Apache HttpComponents() Functioning \n"); } // Simple Crunchify Print Utility private static void printResult(Cord crunchifyResult) { Organization.out.println(crunchifyResult); } }
Simply run above programme and you lot will result as below.
IntelliJ IDEA Console consequence.
File Downloaded Successfully with apache eatables-io Functioning File Downloaded Successfully with Java Stream Performance File Downloaded Successfully with Java NIO ReadableByteChannel Operation File Downloaded Successfully with Files.copy() Performance File Downloaded Successfully with Apache HttpComponents() Operation Procedure finished with exit code 0
Method-one) File Download using apache commons-io
Please brand sure to add below maven dependency into your pom.xml file.
<dependency> <groupId>commons-io</groupId> <artifactId>eatables-io</artifactId> <version>ii.x.0</version> </dependency>

Method-2) File Download using Stream Performance

Method-3) File Download using NIO Operation

Method-four) File Download using Files.copy()

Method-5) File Download using Apache HttpComponents()
Please make sure to add below maven dependency into your pom.xml file.
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>com.springsource.org.apache.httpcomponents.httpclient</artifactId> <version>four.2.1</version> </dependency>

Let me know if you confront any outcome or exception running to a higher place Java Program.
Reader Interactions
How To Download A File In Java,
Source: https://crunchify.com/5-different-ways-to-download-a-file-from-any-given-url-in-java/
Posted by: vernondaventure.blogspot.com
0 Response to "How To Download A File In Java"
Post a Comment