系列索引:Java入门教程索引
一般开发流程为编写Java代码,编译源码为class文件,将class文件打包为jar文件,运行程序。
flowchart LR
A[java] --> B[class]
B --> C[jar]
C --> D[exe]
手动
代码
新建一个文本文件,重命名为HelloWorld.java,添加内容
1 2 3 4 5
| public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
|
编译
使用javac编译java源码,会在同目录生成class文件
1 2 3 4 5 6 7 8 9
| javac HelloWorld.java
Directory: D:\JackeyLea\java
Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 2024/12/30 17:15 425 HelloWorld.class -a--- 2024/12/30 17:13 127 HelloWorld.java
|
运行
使用java执行程序
1 2 3 4
| java HelloWorld
Hello World
|
IDE
为了方便开发,市面上有很多的IDE可以用。开源的Eclipse,开源或者商用的Jetbrains IntelliJ Idea。
可以从Eclipse Packages下载最新版的Eclipse Java。
解压并打开Eclipse。
设置工作空间
显示默认界面
创建新Java工程。
设置工程数据
点击下一步或者结束,没什么区别。
创建一个新class文件,类名helloworld。
添加实现
1 2 3 4 5 6 7
| package helloworld;
public class helloworld { public static void main(String[] args) { System.out.println("Hello World"); } }
|
类名要和文件名相同。
点击菜单或者工具栏编译
在终端显示结果
jar
打包
如果工程比较复杂,可以将一个或者多个class打包为jar文件,方便发布。
1 2 3 4
| jar cvf helloworld.jar helloworld.class
已添加清单 正在添加: helloworld.class(输入 = 555) (输出 = 338)(压缩了 39%)
|
命令执行完成后会在当前目录生成helloworld.jar文件。但是这个jar还无法运行,对应的manifest文件不完整。
解压
执行命令解压jar包
会发现多出来一个META-INF目录和MANIFEST.MF文件,文件内容为
1 2
| Manifest-Version: 1.0 Created-By: 21.0.5 (Eclipse Adoptium)
|
修改为
1 2 3
| Manifest-Version: 1.0 Created-By: 21.0.5 (Eclipse Adoptium) Main-Class: HelloWorld
|
更新打包
执行命令将mf更新到jar中
1
| jar umf .\META-INF\MANIFEST.MF helloworld.jar
|
如果直接将已有mf文件打包到jar中呢?
直接打包
执行打包命令
1 2 3 4 5
| jar cvf helloworld.jar helloworld/helloworld.class .\META-INF\MANIFEST.MF
已添加清单 正在添加: helloworld/helloworld.class(输入 = 555) (输出 = 338)(压缩了 39%) 正在忽略条目META-INF/MANIFEST.MF
|
它主动忽略了mf文件。应该使用其他命令
1 2 3 4
| jar cvfm helloworld.jar .\META-INF\MANIFEST.MF helloworld/helloworld.class
已添加清单 正在添加: helloworld/helloworld.class(输入 = 555) (输出 = 338)(压缩了 39%)
|
此时还不能正常运行,运行报错
1 2 3 4
| java -jar helloworld.jar
错误: 找不到或无法加载主类 helloworld 原因: java.lang.ClassNotFoundException: helloworld
|
应该是目录层级有关。
运行
调整目录层级为
1 2 3 4 5
| ├─helloworld │ helloworld.class │ └─META-INF MANIFEST.MF
|
manifest.mf内容为
1 2 3
| Manifest-Version: 1.0 Created-By: 21.0.5 (Eclipse Adoptium) Main-Class: helloworld.helloworld
|
执行命令打包
1
| jar cvfm helloworld.jar .\META-INF\MANIFEST.MF helloworld/helloworld.class
|
运行
1 2 3
| java.exe -jar helloworld.jar
Hello World
|
感觉按照一般情况下class放置在哪个目录应该是没有关系的。