Magazine
 
Tips ‘n’ Tricks
 

1. Download files data from many
URLs and save them to the local
files in the directory of your choice:


This Java program lets you download files from one or more URLs and save them in the directory where you want. This program takes destination directory for the files to save as first command line argument and URLs for the files as next command line arguments separated by space. Java provides URLConnection class that represents a communication link between the application and a URL. Invoking the openConnection method on a URL creates URLConnection object. Now get InputStream object from that connection and read the data. Finally write the data to the local file.

FileDataDownload.java:

import java.io.*;
import java.net.*;
public class FileDataDownload {
final static int size=1024;
public static void
FileDownload(String fileAddress, String
localFileName, String destinationDir) {
OutputStream os = null;
URLConnection URLConn = null;

// URLConnection class represents a communication link between the
// application and a URL.


InputStream is = null;
try {
URL fileUrl;
byte[] buf;
int ByteRead,ByteWritten=0;
fileUrl= new URL(fileAddress);
os = new BufferedOutputStream(new
FileOutputStream(destinationDir+”\\”+
localFileName));
//The URLConnection object is
created by invoking the

 

// openConnection method on a URL.

URLConn = fileUrl.openConnection();
is = URLConn.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
os.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println(“Downloaded
Successfully.”);
System.out.println(“File name
:\””+localFileName+ “\”\nNo of
bytes :” + ByteWritten);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
os.close();
}
catch (IOException e) {
e.printStackTrace();
}}} public static void fileDownload(String
fileAddress, String destinationDir)
{

// Find the index of last occurance of character ‘/’ and ‘.’.

int lastIndexOfSlash =
fileAddress.lastIndexOf(‘/’);
int lastIndexOfPeriod =
fileAddress.lastIndexOf(‘.’);

// Find the name of file to be downloaded from the address.

String fileName=fileAddress.substring
(lastIndexOfSlash + 1);

// Check whether path or file name is given correctly.

Sept 2007 | Java Jazz Up | 65
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   Download PDF