[java]jar包使用

带包名编译执行

$: cat Demo.java
package com.itheima_03;

public class Demo {
    public static void main(String[] args) {
        System.out.println("maotai");
    }

    public static void show() {
        System.out.println("show");
    }

    public static void add(int a, int b) {
        System.out.println(a + b);
    }
}
$: javac Demo.java
$: java Demo.class
错误: 找不到或无法加载主类 Demo.class
原因: java.lang.ClassNotFoundException: Demo.class
// -d directory, 自动生成包名文件夹

$: javac -d . Demo.java

$: ls com/itheima_03/
Demo.class
//执行报错
$: java Demo
错误: 找不到或无法加载主类 Demo
原因: java.lang.ClassNotFoundException: Demo


//包名+类名  唯一定位一个类
$: java com.itheima_03.Demo
maotai

将class打包为jar包, 供别人使用

$: jar -cvf hello.jar com
已添加清单
正在添加: com/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/itheima_03/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/itheima_03/Demo.class(输入 = 567) (输出 = 361)(压缩了 36%)
//将所有的class文件都打包好了

$: ls hello.jar
hello.jar

$: jar -tf hello.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/itheima_03/
com/itheima_03/Demo.class

//提供给别人使用
idea: file->project structure->library -> 将hello.jar添加到某个(myMehtod)模块下

//他人的myMehtod模块下使用:
package com.itheima_01;

import com.itheima_03.Demo;

public class MethodDemo {
    public static void main(String[] args) {
        Demo.show();
        Demo.add(1,2);
    }
}

jar包中的class是如何被检索到的

$: java -cp ./hello.jar com.itheima_03.Demo
maotai

指定classpath,即可找到: classpath和jar

制作可执行jar包

如何创建可执行的jar包

//压缩带-e ,并指定主类

$: jar -cvfe hello.jar com.itheima_03.Demo com
已添加清单
正在添加: com/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/itheima_03/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/itheima_03/Demo.class(输入 = 567) (输出 = 361)(压缩了 36%)
$: cat MANIFEST.MF
Manifest-Version: 1.0
Created-By: 13.0.2 (Oracle Corporation)
Main-Class: com.itheima_03.Demo  //主类
$: java -jar hello.jar
maotai
原文地址:https://www.cnblogs.com/iiiiiher/p/12359950.html