Skip to content

Instantly share code, notes, and snippets.

@huantt
Created July 6, 2016 10:17
Show Gist options
  • Save huantt/5e008e3716897953a142eeb121940eb4 to your computer and use it in GitHub Desktop.
Save huantt/5e008e3716897953a142eeb121940eb4 to your computer and use it in GitHub Desktop.
package com.huantt.downloader;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Huan on 7/5/2016.
*/
public class Downloader implements Runnable {
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Downloader.class);
private BufferedInputStream bis;
private BufferedOutputStream bos;
private String link;
private String path;
private String fileName;
public Downloader(String link, String path, String fileName) {
this.link = link;
this.path = path;
fileName += getFormatFile();
}
public Downloader(String link, String path) {
this.link = link;
this.path = path;
this.fileName = getFileName();
}
private String getFileName() {
return new String(link.substring(link.lastIndexOf('/') + 1));
}
private String getFormatFile() {
String format = "";
if (link.lastIndexOf(".") != -1) {
format = link.substring(link.lastIndexOf("."));
}
return format;
}
@Override
public void run() {
URL url = null;
try {
url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
bis = new BufferedInputStream(connection.getInputStream());
File file = new File(path + "/" + fileName);
bos = new BufferedOutputStream(new FileOutputStream(file));
} catch (MalformedURLException e) {
log.error(e.toString());
} catch (IOException e) {
log.error(e.toString());
}
byte[] bytes = new byte[1024];
int length;
try {
while ((length = bis.read(bytes)) != -1) {
bos.write(bytes, 0, length);
}
bos.close();
log.info("Finish !");
} catch (IOException e) {
log.error(e.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment