首页 > 代码库 > 使用eclipse打成jar包并且做成批处理bat

使用eclipse打成jar包并且做成批处理bat

(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++;
 }

}


使用eclipse打成jar包并且做成批处理bat