Here is my code for downloading a file from a specified URL using a thread. I want to make it to a multi-threading download, but i cant work it out. And i want to get the downloaded filename is the same as name of the file on URL + part.1,2,3.. etc. Can u guys help me out ? and sorry for my bad english grammar ! My favorite link for test this is : https://docs.oracle.com/javaee/7/JEETT.pdf Thannks all in advance !
public class Threadtest extends Thread {
String s ;
public void InputUrl(){
Scanner sc = new Scanner(System.in);
System.out.println("Input URL :");
s = sc.nextLine();
}
public void run(){
BufferedInputStream bis = null ;
RandomAccessFile raf = null ;
HttpURLConnection conn = null;
URL mUrl = null ;
String a = new File(mUrl.getPath().toString()).getName();
try{
mUrl = new URL(s);
conn = (HttpURLConnection)mUrl.openConnection();
String byteRange = 0+ "-" + 1024;
conn.setRequestProperty("Range", "bytes=" + byteRange);
conn.connect();
bis = new BufferedInputStream(conn.getInputStream());
raf = new RandomAccessFile(a, "rw");
raf.seek(0);
byte[] buffer = new byte[4092];
int count = 0 ;
while ((count = bis.read(buffer,0,4092))!= -1)
{
raf.write(buffer, 0 ,count);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Extending Thread
is not so good idea. Better, by philosophical reason, is to implements Runnable
interface.
class DownloadTask implements Runnable {
private final URL url;
DownloadTask(URL url) {
this.url = url;
}
@Override
public void run() {
// download code
}
}
now we have code to download only. Next step is to use Executor Framework to execute our download tasks.
class Downloader{
private static boolean exitFlag;
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
while(exitFlag) {
URL fileUrl = readUrlFromUserOrSetExit();
pool.execute(new DownloadTask(fileUrl));
}
pool.shutdown();
}
private static URL readUrlFromUserOrSetExit() {
// read from user of set exit flag
}
}
How does it works?
pool
that is responsible for all "thread magic". DownloadTask
instance pool
to execute
. shutdown
executor. It is probably the easiest way if you don't want to use external libs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.