如何通过 Java 命令提示符运行 JAR 文件?
javaobject oriented programmingprogramming更新于 2024/6/30 3:43:00
对于类文件的打包,Java 提供了一种称为 JAR(Java 存档)的文件格式。通常,JAR 文件包含执行应用程序或库所需的 .class 文件、图像、文本文件、库。
此文件格式用于在 Java 中分发应用程序软件和库。所有预定义库都以这种格式提供。
如果您有任何这种格式的库要在应用程序中使用它,您需要将其放在项目的当前(或 lib)文件夹中,或者您需要为该特定 JAR 文件设置类路径。
创建 Jar 文件
Java 提供 jar 命令来处理 jar 文件,如果您在命令提示符中执行它,您将获得此命令的执行语法和选项,如下所示 −
C:\>jar Usage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ... Options: -c create new archive -t list table of contents for archive -x extract named (or all) files from archive -u update existing archive -v generate verbose output on standard output -f specify archive file name -m include manifest information from specified manifest file -n perform Pack200 normalization after creating a new archive -e specify application entry point for stand-alone application bundled into an executable jar file -0 store only; use no ZIP compression -P preserve leading '/' (absolute path) and ".." (parent directory) components from file names -M do not create a manifest file for the entries -i generate index information for the specified jar files -C change to the specified directory and include the following file
您可以使用选项 c、v、f 执行此命令来创建 JAR 文件。以下是使用命令提示符 − 创建 JAR 文件的语法
jar cvf jar_file_name output_path
示例
在路径 D:/example 中创建一个名为 Sample.java 的 java 文件,将以下程序复制并粘贴到其中 −
public class Sample { public static void main(String args[]){ System.out.println("Hi welcome to Tutorialspoint"); } }
使用 javac 命令编译上述程序,文件名为 −
javac Example.java
如果程序执行时没有错误,当前文件夹中将生成 .class 文件。现在,为生成的类创建一个 jar 文件,文件名为 −
C:\Sample>jar cvf sample.jar *.class added manifest adding: Sample.class(in = 434) (out= 302) (deflated 30%) Once you execute a JAR file is generated with the specified name.
使用 eclipse 创建 JAR 文件
您还可以使用 IDE 创建 JAR 文件。要使用 eclipse 创建 JAR 文件,请按照下面给出的步骤 −
打开 eclipse,在其中创建一个项目作为 −
右键单击项目文件夹并选择 Export 选项作为 −
在 Java 类别下选择 JAR 文件。
单击下一步。
输入 JAR 文件名和文件夹。
单击完成。