Java File Download Example

To make an application that downloads the file from the remote locations, you might used to follow the steps as given below.

Java File Download Example

To make an application that downloads the file from the remote locations, you might used to follow the steps as given below.

Java File Download Example

Java File Download Example

To make an application that downloads the file from the remote locations, you might used to follow the steps as given below,

1. Make an object of java.net.URL, and pass the url of the the remote file, which you have to download as,

URL url = new URL("http://www.roseindia.net/java/beginners/CreateDirectory.java");
Here http://www.roseindia.net/java/beginners/CreateDirectory.java is a download URL, which is being passed in URL constructor.

2. Now make an object of java.io.BufferedInputStream class to open the stream and create a buffer of the for the file.
BufferedInputStream bufferedInputStream = new BufferedInputStream(url.openStream());
3. Create an object of java.io.FileOutputStream and java.io.BufferedOutputStream that writes the data to the new file.
FileOutputStream fileOutputStream =new  FileOutputStream("sampleFile.txt");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream, 1024);

Here "sampleFile.txt" is the name of the new file. 4. And then create an array of bytes and initiate a loop that will read data from the bufferedInputStream and write it the bufferedOutputStream as

byte data[] = new byte[1024];
while(bufferedInputStream.read(data, 0, 1024) >=0 )
{
	bufferedOutputStream.write(data);
}

5. And finally close both buffers as

bufferedOutputStream.close();
bufferedInputStream.close();

The Complete source code is given below,

SampleInterfaceImp.java

import java.io.*;
import java.net.*;

public class JavaFileDownloadExample{
	public static void main(String[] args) throws IOException{

		String fileUrl= "http://www.roseindia.net/java/beginners/CreateDirectory.java";
		URL url = new URL(fileUrl);
		BufferedInputStream bufferedInputStream = new BufferedInputStream(url.openStream());
		FileOutputStream fileOutputStream =new  FileOutputStream("sampleFile.txt");
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream, 1024);

		byte data[] = new byte[1024];
		while(bufferedInputStream.read(data, 0, 1024) >=0 )
		{
			bufferedOutputStream.write(data);
		}

		bufferedOutputStream.close();
		bufferedInputStream.close();
	}				
}

When you will run the example you will get the new file named sampleFile.txt

Download Select Source Code