工程包文件:commons-io-1.1.jar、config.properties、download.jar、start.bat
说明:借助Apache Commons IO工具包(commons-io-1.1.jar)来简单实现文件(夹)的复制、移动、删除、获取大小等操作
config.properties 文件内容:
#远程服务器下载url
remoteUrl=http://localhost:8080/test/download/a.mp3
#下载文件保存位置如F:\download
saveFileUrl=F
#并发下载线程数
threadNums=10
start.bat文件内容:
set classpath=download.jar;commons-io-1.1.jar
java FileSave
pause
download.jar 文件主class文件源码:
import java.io.File;
import java.net.URL;
import java.util.Random;
import org.apache.commons.io.FileUtils;
public class FileSave
{
static String remoteUrl = "http://192.168.100.15:8080/myweb/001232.mp3";
static String saveFileUrl = "D:/download/";
public static void main(String[] args)
{
for (int i = 0; i < 500; i++)
{
new Thread(new myThread(remoteUrl, saveFileUrl)).start();
}
}
}
class myThread implements Runnable
{
int NUM = 1;
String remoteUrl = "";
String saveFileUrl = "";
public myThread(String remoteUrl, String saveFileUrl)
{
this.remoteUrl = remoteUrl;
this.saveFileUrl = saveFileUrl;
}
public void run()
{
downloadFromUrl(remoteUrl, saveFileUrl);
}
/**
* 文件下载的方法
*/
public static String downloadFromUrl(String url, String dir)
{
String fileName = "";
try
{
URL httpurl = new URL(url);
String[] us = url.split("/");
fileName = us[us.length - 1];
String ramdom = System.currentTimeMillis() + ""
+ new Random().nextInt(100);
fileName = ramdom + "_" + fileName;
System.out.println("fileName:" + fileName);
File f = new File(dir + fileName);
FileUtils.copyURLToFile(httpurl, f);
} catch (Exception e)
{
e.printStackTrace();
return "Fault!";
}
return fileName;
}
}