JAVA命令行运用
参考:学习链接
使用cmd运行java文件
使用命令:cd进入文件所在路径,javac编译.java文件
遇到的问题:错误: 找不到文件: Pump.java
原因:使用文本文档写代码时隐藏了文件后缀,默认后缀仍为.txt,需要改变文件属性
编译成功后在当前路径产生.class文件。
使用命令:java执行.class文件,得到如下结果:
D:\PractiseJava>java PumpTest
Type of pump:swashplate pump
Rotate speed:4200rpm
Output pressure:21.5MPa
Weught:9.8kg
Displacement:19.5ml/rev
Pulsation:4.0%
Type of pump:swashplate pump
Rotate speed:4000rpm
Output pressure:28.0MPa
Weught:15.3kg
Displacement:75.0ml/rev
Pulsation:4.0%
java命令执行的是带有main方法的类。
命令行使用方法用java -h命令查看。
执行类命令:java [options] <主类> [args…]
options选项中 -D命令使用方法:-D<名称>=<值>
用于设置系统属性,该值是查找对象的依据。
使用命令行打jar包和引用
在命令行输入jar显示jar不是内部或外部命令错误,解决方案:
1)检查java环境变量,参考环境配置
2)在用户变量的Path中添加java的bin文件夹所在路径
jar命令可以运行后开始测试打jar包。
使用测试代码:
Test1.java
/**
* this is a test class
* @author XYM_
* @date 2021-4-13
* @version 1.0
*/
package com.test1;
public class Test1{
/**
* print the test sentence
* @author XYM_
* @version 1.0
*/
public void display(){
//print the sentence
System.out.println("This is test1");
}
}
Test2.java
/**
* this is a test class
* @author XYM_
* @date 2021-4-13
* @version 1.0
*/
package com.test2;
public class Test2{
/**
* print the test sentence
* @author XYM_
* @version 1.0
*/
public void display(){
//print the sentence
System.out.println("This is test2");
}
}
Main.java
/**
* this is a main class
* @author XYM_
* @date 2021-4-13
* @version 1.0
*/
package com.main;
import com.test1.Test1;
import com.test2.Test2;
public class Main {
public static void main(String[] args) {
for(String a:args) {
System.out.println("参数" + a);
}
Test1 t1 = new Test1();
t1.display();
Test2 t2 = new Test2();
t2.display();
}
}
在foo文件夹中创建包的结构文件夹,包含com以及下属test1,test2和main
在当前目录下编译测试代码:
javac -d . Test1.java Test2.java Main.java
编译成功后把class文件放入对应包目录中。
创建清单文件MANIFEST.MF:
Manifest-Version: 1.0
Main-Class: com.main.Main
注意:冒号后加空格,最后一行为空行
清单文件指明了需要执行的主类
打包命令:
jar cvfm t2.jar MANIFEST.MF -C foo/ .
运行结果:
已添加清单
正在添加: com/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/main/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/main/Main.class(输入 = 1071) (输出 = 622)(压缩了 41%)
正在添加: com/test1/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/test1/Test1.class(输入 = 405) (输出 = 284)(压缩了 29%)
正在添加: com/test2/(输入 = 0) (输出 = 0)(存储了 0%)
正在添加: com/test2/Test2.class(输入 = 405) (输出 = 285)(压缩了 29%)
执行jar包,:
D:\PractiseJava\Test>java -jar t2.jar 1 2 3
参数1
参数2
参数3
This is test1
This is test2
创建Test.java:
import com.test1.Test1;
import com.test2.Test2;
public class Test {
public static void main(String[] args) {
for(String a:args) {
System.out.println("参数" + a);
}
Test1 t1 = new Test1();
t1.display();
Test2 t2 = new Test2();
t2.display();
}
}
引用jar包编译:
javac -cp t2.jar Test.java
编译后执行:
D:\PractiseJava\Test>java -classpath t2.jar; Test
This is test1
This is test2
引用完成。