Home Java Examples Io Java File Download Example



Java File Download Example
Posted on: January 18, 2012 at 12:00 AM
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,

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

Related Tags for Java File Download Example:


More Tutorials from this section

Ask Questions?    Discuss: Java File Download Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.