在myJava/com/test目录下文本编辑一个文件hello.java,内容如下:
packege com.test;
public class hello{
public static void main(String[] args)
{
System.out.println("hello wood!");
}
}
编译:
在myJava目录下执行javac com/test/hello.java
编译后会在myJava/com/test目录生成一个hello.class文件
运行:
在myJava目录执行java com.test.download
打包:
编辑一个manifest.txt文件,只有一行,这个文件的作用是告诉执行时的入口main函数在那个类
Main-Class: com.test.hello
在myJava目录执行jar -cfm my.jar manifest.txt com
生成my.jar
执行java -jar my.jar即可运行程序,输出
hello wood!
如果要引用第三方jar包,需要设置classpath,两种方法:
1、javac -classpath jar包路径/xxx.jar 要编译的java文件
2、export $CLASSPATH=jar包路径/xxx.jar
然后在java文件中import就好
有时候我们可能需要把打包好的jar传送到其他地方运行,如果运行的环境没有某些依赖的jar包就会报错java.lang.NoClassDefFoundError
这时候就需要把缺失的jar包解压出来一起打包:
jar -cfm my.jar manifest.txt com jar包解压出来的目录1 jar包解压出来的目录2 ...
如:jar -cfm my.jar manifest.txt com org javax
参考:http://kuring.me/post/compile_java_code
http://blog.youkuaiyun.com/huagong_adu/article/details/6929817
http://www.jianshu.com/p/61cfa1347894