本文只介绍实用步骤,预备知识请自查阅:
参考资料:
http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html
http://www.skylit.com/javamethods/faqs/createjar.html
http://geeksun.iteye.com/blog/464690
http://stackoverflow.com/questions/18146361/how-to-create-jar-file-with-package-structure
-----------------------------------------------------------
一 未引用外部包的类文件打包:
1、例如我在目录:E:\eclipse 下创建helloworld.java:
public class helloworld { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello World!!"); } }
cd /d e:\eclipse
2、编译helloworld.java:
e:\eclipse>javac helloworld.java
3、进行打包工作:
e:\eclipse>echo Main-Class: helloworld> manifest.txt
e:\eclipse>jar cvfm hello.jar manifest.txt helloworld.class
标明清单(manifest)
增加:helloworld.class(读入= 427) (写出= 290)(压缩了 32%)
e:\eclipse>java -jar hello.jar
Hello World!!
提醒:manifest.txt文件格式一定要注意:The text file must end with a new line(新起一行) or carriage return(回车)
二 引用外部包的类文件打包:
1、在路径:E:\eclipse\ftpTools\src 下有一个Hello.java 文件:
import org.apache.log4j.Logger; public class Hello { static Logger logger = Logger.getLogger(Hello.class); public static void main(String[] args) { // TODO Auto-generated method stub logger.error("Hello world."); logger.info("What a beatiful day."); } }
E:\eclipse\ftpTools\src>javac -classpath lib\log4j-1.2.9.jar Hello.java
PS:两种方式配置classpath,①将引用的JAR包拷贝到JAVA_HOME\lib文件夹下,配置环境变量CLASSPATH,这样可直接javac Hello.java;
例如:;%JAVA_HOME%\lib\commons-net-3.3.jar;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\commons-io-2.4.jar;%JAVA_HOME%\lib\log4j-1.2.9.jar
②编译时实用-classpath参数指定引用的JAR包路径;
3、进行打包工作:
3.1 创建好manifest.txt文件:
Manifest-Version: 1.0
Class-Path: lib\log4j-1.2.9.jar lib\commons-io-2.4.jar lib\commons-net-3.3.jar
Main-Class: Hello
3.2 运行JAR:
E:\eclipse\ftpTools\src>jar cvfm Hello.jar manifest.txt log4j.properties Hello.c
lass
标明清单(manifest)
增加:log4j.properties(读入= 1229) (写出= 380)(压缩了 69%)
增加:Hello.class(读入= 594) (写出= 378)(压缩了 36%)
E:\eclipse\ftpTools\src>java -jar Hello.jar
2013-12-15 14:50:01 ERROR Hello:12 - Hello world.
2013-12-15 14:50:01 INFO Hello:13 - What a beatiful day.
PS:此处实用的例子文件在一下链接可进行下载:
http://download.csdn.net/detail/indexman/6717405
---------------------------------
Dylan presents.