Java url get files

How to Download a File from a URL in Java

Are you looking to create your very own application that can download any file with a single click? If you want such a feature in your Java application, you are in the right place. Many developers require such file downloading features in their Java application. In this article, you will learn how to download a file using a URL in Java.

What is downloading a file using a URL?

Downloading a file through a Java code using a URL allows the Java application to download a file directly into a local system from a remote repository or any other local storage. This process reads a file from the URL and writes it to a local file. Java offers three different ways to download a file using a URL.

1: Plain Java structure:

If we use Java without using any external library, it takes the file as input and reads those data byte by byte. Now, if we take the byte-by-byte data from an input stream & write the bytes to a file output stream, we can achieve downloading using URL.

import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.net.URL; class Main< public static void URLDnldFile(URL urlink, String fileName) throws IOException< try (InputStream inp = urlink.openStream(); BufferedInputStream bis = new BufferedInputStream(inp); FileOutputStream fops = new FileOutputStream(fileName))< byte[] d = new byte[1024]; int i; while ((i = bis.read(d, 0, 1024)) != -1)< fops.write(d, 0, i); >>> public static void main(String[] args) throws Exception< System.out.println("Call this method when you want your application to have this."); //Call the URLDnldFile() method >>

Explanation:

Here, we have to import the BufferInputStream, FileInputStream, InputStream, IOException, and java.net.URL. Now, create a Main class with a method URLDnldFile() that throws IO exception. The function uses two parameters, one URL link and the other file name. Create a variable ‘d’ of type byte. The stream of bytes will be read within this method using the while loop.

2: Using Java.IO package:

java.io is the traditional Java package that contains various classes. It has some built-in classes used explicitly for reading &writing to a stream.

import java.net.URL; import java.net.URLConnection; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main < public static void main(String[] args)< OutputStream ops = null; InputStream ins = null; String fileLink = "http://200.156.21.23:8080/karlos/project1.txt"; String oppath = "G:\\Downloads\\urlfile.txt"; try < URL url = new URL(fileLink); URLConnection connection = url.openConnection(); ins = connection.getInputStream(); ops = new FileOutputStream(oppath); final byte[] bt = new byte[1024]; int len; while ((len = ins.read(bt)) != -1)< ops.write(bt, 0, len);>>catch (IOException ex)< ex.printStackTrace(); >finally< // close streams System.out.println("URL's File downloaded. "); >>>

Explanation:

Here, we have to import the URLConnection, FileOutputStream, IOException, InputStream, and OutputStream. Within the main(), create a OutputStream and InputStream object and two string variables to hold the URL link and file location. Within the try block, set the URL and the URLConnection using getInputStream(). The following catch block will handle any input-output exception and execute the printStackTrace(). The finally block (which executes automatically as a mandatory part of the program) will display the message “URL’s File downloaded.”

Читайте также:  Ajax methods in php

3: Using NIO:

Java NIO (abbreviated as New IO) is an alternative input-output Java API that also comes as a Java package. The NIO acts as an alternative to the standard Java IO and Java Networking API. While using the Java IO library, the streams read the data byte by byte. But in the Java NIO package, data are read as channels and buffers.

import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.io.File; public class Main < public static void main(String[] args)< try< String fileLink = "http://200.156.21.23:8080/karlos/project1.txt"; String oppath = "G:\\Downloads\\urlfile.txt"; URL link = new URL(fileLink); InputStream ins = link.openStream(); ReadableByteChannel chh = Channels.newChannel(link.openStream()); FileOutputStream fos = new FileOutputStream(new File(oppath)); fos.getChannel().transferFrom(chh, 0, Long.MAX_VALUE); fos.close(); chh.close(); >catch(IOException ex)< ex.printStackTrace(); >>>

Explanation:

Here, we have to import the URL, Channels (which is a part of NIO package), FileOutputStream, IOException, InputStream OutputStream, and java.io.File. Now, within the Main class, we have created the main(). Inside the main() and within the try block, we have created two String objects by the name fileLink and oppath where we have defined the URL link and the file location. Then we have created an input stream for the file we want to download. Then, we have to produce a new channel responsible for reading the data from this input stream. Next, we have to create an output stream that will write the file contents after putting it from the channel object. Now, we have to fetch the channel from this output stream & define its contents from the channel. The following catch block will handle any input-output exception and execute the printStackTrace().

4: Using Apache Commons IO:

Apache Commons IO is a utility package of Java that has an org.apache.commons.io.FileUtils class. It comprises a copyURLToFile method that can help program IO operations. This method takes 2 arguments – The first is the java.net.URL object that points to the source file while the second is the java.io.File object pointing to the output file path. Note that both paths should consist filename at the end. The output path should be the file location on your local system from where the file will get downloaded.

import org.apache.commons.io.FileUtils; public class Main < public static void main(String[] args) < String fileLink = "http://200.156.21.23:8080/karlos/proj.zip"; String oppath = "G:\\downloads\\proj.zip"; FileUtils.copyURLToFile(new URL(fileLink), new File(oppath)); >> You can further append Apache Commons IO dependency in your project.   org.apache.commons commons-io 1.3.2  // Gradle compile group: ‘org.apache.commons’, name: ‘commons-io’, version: ‘1.3.2’

Explanation:

First, we have to import apache.commons.io.FileUtils. Within the Main class, we have to create the main() inside which we have to create two String variables to hold the URL link and file location. Now, use the FileUtils.copyURLToFile() method to make the program download a file (from the specified location) using the URL (given). This method is taking two parameters fileLink and oppath, that we have created earlier.

Читайте также:  Python range бесконечное число

Among these four techniques, Apache Commons IO is the easiest one. But it increases the program size and reduces speed due to external library inclusion. Method 2, which uses the pre-existing IO package is the fastest, but not the latest approach. New Input-Output (NIO package), as the name suggests, is the latest IO package which is an alternative to the IO package, can also benefit you if you want to perform different and latest I/O operations within your program.

  • Java Training Tutorials for Beginners
  • How Java Programming Works
  • Polymorphism in Java
  • Abstract Class vs Interface
  • Palindrome in Java
  • Decimal to Binary
  • Comparable vs Comparator
  • Remove Duplicates from Array
  • Difference between Error and Exception
  • Difference between Array and ArrayList
  • Java Calculator
  • Difference between Throw and Throws
  • Best Java Online Compilers
  • Error Could not find or load main class
  • Difference between SDM and JSPM
  • Eclipse IDE Download & Installation
  • Java Program using Eclipse IDE
  • SAP JCo Tutorial
  • Packages in Java
  • Java Interview Questions

Источник

Java download file

Often it is required to download a file directly from a URL and save to a directory on local system such as downloading a file from a remote repository. This requires reading a file from url and writing it to a local file.
This article will share different methods to download a file from URL in java. Methods defined here are applicable to all types of file such as a pdf file, an exe file, a txt file or a zip file etc.

  1. Create a connection to the given file url.
  2. Get input stream from the connection. This stream can be used to read file contents.
  3. Create an output stream to the file to be downloaded.
  4. Read the contents from the input stream and write to the output stream.

Java code to download file from URL with this method is given below.

import java.net.URL; import java.net.URLConnection; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileDownloader < public static void main(String[] args) < OutputStream os = null; InputStream is = null; String fileUrl = "http://200.34.21.23:8080/app/file.txt"; String outputPath = "E:\\downloads\\downloaded.txt"; try < // create a url object URL url = new URL(fileUrl); // connection to the file URLConnection connection = url.openConnection(); // get input stream to the file is = connection.getInputStream(); // get output stream to download file os = new FileOutputStream(outputPath); final byte[] b = new byte[2048]; int length; // read from input stream and write to output stream while ((length = is.read(b)) != -1) < os.write(b, 0, length); >> catch (IOException e) < e.printStackTrace(); >finally < // close streams if (os != null) os.close(); if (is != null) is.close(); >> >

Remember that the output and input paths should end with the file name else there will be an error.

All the methods in this post read a file at a remote URL. If you want to read a file at local system, then refer this post.

  1. Create an input stream to the file to be downloaded.
  2. Create a new channel that will read data from this input stream.
  3. Create an output stream that will write file contents after reading it from the channel created in Step 2.
  4. Get the channel from this output stream and write the contents from channel created in Step 2.
Читайте также:  Java mobile games development

You will understand the algorithm better after looking at the below code example.

import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.io.File; public class FileDownloader < public static void main(String[] args) < try < String fileUrl = "http://200.34.21.23:8080/app/file.pdf"; String outputPath = "E:\\downloads\\downloaded.pdf"; URL url = new URL(fileUrl); // create an input stream to the file InputStream inputStream = url.openStream(); // create a channel with this input stream ReadableByteChannel channel = Channels.newChannel( url.openStream()); // create an output stream FileOutputStream fos = new FileOutputStream( new File(outputPath)); // get output channel, read from input channel and write to it fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); // close resources fos.close(); channel.close(); >catch(IOException e) < e.printStackTrace(); >> >

Note that transferFrom() method of a channel takes 3 arguments.
1. input file channel,
2. position at which it will start reading the file, 0 here means the beginning of file, and
3. number of bytes that will be transferred at one time. This value is set to a very large value( Long.MAX_VALUE ) for higher efficiency.

Learn different methods of writing to a file here .

Method 3 : Using Apache Commons IO Library
Apache Commons IO Library has a org.apache.commons.io.FileUtils class which contains a method copyURLToFile() .

This method takes two arguments:
1. java.net.URL object pointing to the source file, and
2. java.io.File object which points to an output file path.

Remember that both paths should contain the name of file at the end and output path should be a location on local system at which the file will be downloaded.
copyURLToFile() reads the file from remote location and copies it to the local machine. Example,

import org.apache.commons.io.FileUtils; public class FileDownloader < public static void main(String[] args) < String fileUrl = "http://200.34.21.23:8080/app/file.zip"; String outputPath = "E:\\downloads\\downloaded.zip"; FileUtils.copyURLToFile(new URL(fileUrl), new File(outputPath)); >>

You can add Apache Commons IO dependency to your project as per the build tool.

// Gradle
compile group: ‘org.apache.commons’, name: ‘commons-io’, version: ‘1.3.2’

Hope the article was useful in explaining different ways to download a file from URL in java.
Do not forget to click the clap below.

Источник

Java url get files

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью