(1)打包jar方法:右鍵工程名--export--jar File--勾選需要打包的文件(默認即可)
(2)做批處理:編寫start.bat ,內容如:
set classpath=download.jar;commons-io-1.1.jar //這裏所需第三方jar,和(1)打的jar都要指定,以分號間隔
java FileSave //這裏是含有main方法的類名
pause
補充:業務jar包需要讀取properties文件,這個路徑在未打包之前是相對於根目錄的,打包之後,如果不在jar包添加properties文件,就會爆properties文件找不到。
所以,最好包配置文件放到工程的根目錄,打成jar之後,放到同級目錄中。
例子:config.properties位於改成根目錄
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.Random;
import org.apache.commons.io.FileUtils;
public class FileSave
{
static String remoteUrl = "";
static String saveFileUrl = "";
static int threadNums = 0;
public static void main(String[] args) throws IOException
{
// 讀取配置文件
readConfig();
for (int i = 0; i < threadNums; i++)
{
new Thread(new myThread(remoteUrl, saveFileUrl)).start();
}
}
public static void readConfig() throws IOException
{
String fp = System.getProperty("user.dir") + File.separator
+ "config.properties";
File file = new File(fp);
Properties properties = new Properties();
java.io.FileInputStream in = new java.io.FileInputStream(file);
properties.load(in);
in.close();
remoteUrl = properties.getProperty("remoteUrl");
saveFileUrl = properties.getProperty("saveFileUrl") + ":/download/";
threadNums = Integer.parseInt(properties.getProperty("threadNums"));
}
}
class myThread implements Runnable
{
static long NUM = 0;
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) + new Random().nextInt(100)
+ new Random().nextInt(100) + getSequence();
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;
}
public static synchronized long getSequence()
{
if (NUM > 100000000)
{
NUM = 0;
}
return NUM++;
}
}