随笔-50  评论-55  文章-8  trackbacks-0
前言:用myEclipse打包可执行jar文件,特别是需要包含第三方资源包的时候,往往打包好之后jar文件找不到,即使 manifest.mf 文件设置了ClassPath= ?.jar 之类的,还会找不到第三方资源包的问题;一般情况下,第三方资源包都不应该和你的应用程序打成一个包,而是作为外部文件引入,这个时候需要考虑用classloader的方式打包。

步骤一:
      自己的程序先打一个包my.jar(可以是不可执行的),这个不包含第三方资源包(如log4j.jar);用myeclipse的export方式可以搞定;

步骤二:
     写一些加载第三方资源包的类,这里可以参考这个类(网上找的

import java.io.*;  
import java.net.*;  
import java.lang.reflect.*;  
 
public class BootLoader  
{  
  public static void main(final String[] args) throws Exception  
  {  
    // check that the lib folder exists  
    File libRoot = new File(LIB_FOLDER);  
    if(!libRoot.exists()) {  
      throw new Exception("No 'lib' folder exists!");  
    }  
    // read all *.jar files in the lib folder to array  
    File[] libs = libRoot.listFiles(new FileFilter()  
    {  
      public boolean accept(File dir)  
      {  
        String name = dir.getName().toLowerCase();  
        return name.endsWith("jar") || name.endsWith("zip");  
      }  
    });  
 
    URL[] urls = new URL[libs.length];  
    // fill the urls array with URLs to library files found in libRoot  
    for(int i = 0; i < libs.length; i++) {  
      urls[i] = new URL("file",null,libs[i].getAbsolutePath());  
    }  
    // create a new classloader and use it to load our app.  
    classLoader = new URLClassLoader(urls,  
                                     Thread.currentThread().  
                                     getContextClassLoader());  
    // get the main method in our application to bring up the app.  
    final Method mtd = classLoader.loadClass(APP_MAIN_CLASS).getMethod("main",  
        new Class[] {String[].class});  
    // Using thread to launch the main 'loop' so that the current Main method  
    // can return while the app is starting  
    new Thread(new Runnable()  
    {  
      public void run()  
      {  
        try {  
          mtd.invoke(null,new Object[] {args});  
        } // forward the args  
        catch(Exception e) {  
          throw new RuntimeException(e);  
        }  
      }  
    },"AppMain").start();  
    // Give the app some time to start before returning from main.  
    // This doesn't delay the starting in any way  
    Thread.sleep(1000);  
  }  
 
  private static final String LIB_FOLDER = "lib";   //所有第三方包放在这个文件夹下
  private static final String APP_MAIN_CLASS = "com.monitor.Main";   //可执行文件的入口程序,也是你自己代码的一个包含main函数的类
  private static ClassLoader classLoader;  

再将这个独立的类打包成可执行文件main.jar(不包含第三方资源包)

步骤三:组织好各个文件
比如在文件下F:/存在 文件
main.jar
lib(文件夹,lib文件夹下 放:my.jar ,log4j.jar,等等)
config.properties(如果有配置文件)
logo.jpg(如果有外部图片)
可以写个批处理文件main.bat 内容: java  -Xms100m   -Xmx800m  -jar main.jar
双击main.bat 即可执行
posted on 2008-07-17 11:16 蒋家狂潮 阅读(1837) 评论(1)  编辑  收藏 所属分类: Basic

评论:
# re: 用classloader方式打包可执行jar文件[未登录] 2008-07-17 14:35 | paul
你安装fatjar,还用这么费劲啊  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: