大连 做网站公司,个人主页网页设计源代码,上海哪家公司提供专业的网站建设,12306 网站开发被导入的外部类所在源文件通常要打包成jar包#xff0c;java中的jar文件装的是 .class 文件。它是一种压缩格式和zip兼容#xff0c;被称为jar包。JDK提供的许多类#xff0c;也是以jar包的形式提供的。在用的时候呢#xff0c;你的文件里有很多个类#xff0c;把这些类和…被导入的外部类所在源文件通常要打包成jar包java中的jar文件装的是 .class 文件。它是一种压缩格式和zip兼容被称为jar包。JDK提供的许多类也是以jar包的形式提供的。在用的时候呢你的文件里有很多个类把这些类和他们的目录一起压缩到一个文件中发布出去的。使用者拿到这个jar包之后只要让CLASSPATH的设置中包含这个jar文件java虚拟机在装载类的时候就会自动解压这个jar文件并将其当成目录然后在目录中查找我们所要的类及类的包名和所对应的目录的结构。jar包的打包步骤如下[rootlocalhost test]# javac -d . Shoes.java #编译[rootlocalhost test]# jar -cvf shoejar.jarcom #打包注意将目录也要包含进去added manifestadding: com/(in 0) (out 0)(stored 0%)adding: com/dangdang/(in 0) (out 0)(stored 0%)adding: com/dangdang/shoe/(in 0) (out 0)(stored0%)adding: com/dangdang/shoe/Shoes.class(in 771)(out 466)(deflated 39%)这样就得到了一个jar包我们可以使用unzip解压验证一下如[rootlocalhost test]# unzip shoejar.jarArchive: shoejar.jarcreating:META-INF/inflating:META-INF/MANIFEST.MFcreating:com/creating:com/dangdang/creating: com/dangdang/shoe/inflating:com/dangdang/shoe/Shoes.class可见jar包中只有类文件。拿到jar包后该如何使用假如jar包存放在如下位置[rootlocalhost test]# tree.├──Clothes.java└──jar└──shoejar.jar1 directory, 3 files[rootlocalhost test]#首先编译主类文件这需要使用-cp或-classpath指定主文件运行所依赖的其他.class文件所在的路径。我们尝试编译Clothes.java文件。如[rootlocalhost test]# javac -cp ./jar/* Clothes.java[rootlocalhost test]#编译成功运行类文件但是情况不妙报找不到Class异常[rootlocalhost test]# java Clothesim making a XL size cloth with color redException in thread mainjava.lang.NoClassDefFoundError: com/dangdang/shoe/ShoeatClothes.main(Clothes.java:26)Caused by: java.lang.ClassNotFoundException:com.dangdang.shoe.Shoeatjava.net.URLClassLoader.findClass(URLClassLoader.java:381)at java.lang.ClassLoader.loadClass(ClassLoader.java:424)atsun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)atjava.lang.ClassLoader.loadClass(ClassLoader.java:357)... 1more这是因为jar包中的类文件无法进行加载。我们再次使用-cp参数指定依赖类路径运行[rootlocalhost test]# java -cp jar/* ClothesError: Could not find or load main class Clothes[rootlocalhost test]#因为cp只指定了依赖类所在的jar目录覆盖了默认的搜索路径即当前目录(即.)而当前目录是Clothes.class文件所在目录因此要运行这个.class字节码文件需要将当前目录也加进来(用:隔开)系统才能找到当前目录下的Java类。[rootlocalhost test]# java -cp .:jar/* Clothes #指定搜索路径im making a XL size cloth with color redim making a pair of shoes with color red and size41[rootlocalhost test]# ll我们也可以使用java本身的类加载功能即可以把需要加载的jar都扔到JRE_HOME/lib/ext下面这个目录下的jar包会在Bootstrap Classloader工作完后由Extension Classloader来加载。[rootlocalhost test]# cp jar/shoejar.jar/usr/java/jdk1.8.0_181/jre/lib/ext/[rootlocalhost test]# javac Clothes.java #编译[rootlocalhost test]# java Clothesim making a XL size cloth with color redim making a pair of shoes with color red and size41