This code is extracted from one of my projects and the unnecessary parts are removed.
This method was set to be invoked by an interface designed to give inputs for download manager. Using a simple interface you can give the necessary inpluts.
public void save(final String urlString, final String fileDestination) throws IOException {
Thread downloaderThread = new Thread(new Runnable() {
URL url = new URL(urlString);
InputStream is = url.openStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] b = new byte[2048];
int length = -2;
long totalFileSize = Util.getFileSize(url);
float currentFileSize = 0;
@Override
public void run() {
try {
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
currentFileSize += length;
frame.updateProgressbar((int) (currentFileSize
/ totalFileSize * 100));
}
is.close();
os.close();
byte[] response = os.toByteArray();
FileOutputStream fos = new FileOutputStream(fileDestination+ "\\" + Util.getFileName(url));
fos.write(response);
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} });
downloaderThread.setPriority(10);
downloaderThread.start();
}
Inputs needed:
-The URL of the file to be downloaded.(The URL of the internet link)
-The destination of the folder that you are going to save the file into.(In your PC)
It's a thread that runs to save the file.If you do not have thread knowledge yet you can ignore that part and consider the following.
public void save(final String urlString, final String fileDestination) throws IOException {
Thread downloaderThread = new Thread(new Runnable() {
//here is the rest of the code
@Overrride
public void run(){
//here is the rest of the code
}
});
downloaderThread.setPriority(10);
downloaderThread.start();
}
The above code is used to make it a thread invocation.Without the thread part the method would look like ,
public void save(String urlString, String fileDestination) throws IOException {
URL url = new URL(urlString); //making URL object using the URLString
InputStream is = url.openStream(); //opening an input stream using URL
ByteArrayOutputStream os = new ByteArrayOutputStream();
//Setting an output stream to write into
byte[] b = new byte[2048]; //this byte array is used as a buffer
int length = -2;
long totalFileSize = Util.getFileSize(url);
//Util is a utility class that contains methods for getting file name,file size etc
float currentFileSize = 0;
//this is used for measuring total file size(optional)
try {
while ((length = is.read(b)) != -1) {
//input stream 'is' is read into buffer 'b'
os.write(b, 0, length); //writing into 'os' output stream
currentFileSize += length; //accumulating total length
frame.updateProgressbar((int) (currentFileSize
/ totalFileSize * 100));
//updating a progressbar(optional)
}
is.close();
os.close(); //closing input and output streams
byte[] response = os.toByteArray();
//output stream into a byte array
FileOutputStream fos = new FileOutputStream(fileDestination+ "\\" + Util.getFileName(url));
//getting a file output stream that specifies the file destination and
//here the name of the file is acquired from thu Util class
fos.write(response);
fos.close(); //closing the file output streams
} catch (IOException e1) {
e1.printStackTrace();
}
}
I have gray coloured a few lines of code that is related with updating a pregressbar while being downloaded.So, the idea is,
-Opening an input stream from the URL object
-Reading the input stream using a byte array
-Writing that read byte array into an output stream
-Loop till the input stream reaches the end
-Get the output stream into another byte array which contains the
whole content
-Write that byte stream into a file using a file output stream
Here is the Util class that I implemented for getting necessary details.
I implemented that as a static inner class inside the class that contained the above code. So don't get confused with the static keyword, behind the class definition.... :)
public static class Util {
public static float getDownloadSpeed(float byteLength, long startTime,
long endTime) {
float speed = (float) byteLength / (endTime - startTime) * 1000
/ 1024;
System.out.println(speed);
return speed;
}
public static String getFileName(URL filrUrl) {
String[] arrayOfFields = filrUrl.getFile().trim().split("&");
if (arrayOfFields != null) {
for (int i = 0; i < arrayOfFields.length; i++) {
if (arrayOfFields[i].startsWith("title=")) {
return arrayOfFields[i].substring(6).replaceAll("[+]",
" ");
}
}
}
return "untitled.File";
}
public static String getFileExtension(String url) {
String extension = FilenameUtils.getExtension(url);
if (extension != null) {
return extension;
}
return "File";
}
public static long getFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLengthLong();
} catch (IOException e) {
return -1;
} finally {
conn.disconnect();
}
}
}
Comments
Post a Comment