Java程序示例通过配置文件获取jar包地址、名字并加载程序中判断地址末尾是否包含斜杠、自动拼接jar包地址获取jar包时判断是否存在使用命令行的方式调用jar包且指定传参
以下是一个示例的Java程序,通过配置文件获取jar包地址和名字,并加载程序中判断地址末尾是否包含斜杠,自动拼接jar包地址。然后检查jar包是否存在,最后使用命令行的方式调用jar包并指定传参。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
try {
// 读取配置文件
Properties properties = new Properties();
FileInputStream fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);
// 获取配置信息
String jarPath = properties.getProperty("jarPath");
String jarName = properties.getProperty("jarName");
String parameter = properties.getProperty("parameter");
// 判断地址末尾是否包含斜杠
if (!jarPath.endsWith(File.separator)) {
jarPath += File.separator;
}
// 拼接jar包地址
String jarFilePath = jarPath + jarName;
// 检查jar包是否存在
File jarFile = new File(jarFilePath);
if (!jarFile.exists()) {
System.out.println("Jar file does not exist!");
return;
}
// 使用命令行的方式调用jar包并指定传参
String command = "java -jar " + jarFilePath + " " + parameter;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
// 输出命令行执行结果
int exitValue = process.exitValue();
System.out.println("Command execution completed with exit value: " + exitValue);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
配置文件 config.properties 样例:
jarPath=/path/to/jar/
jarName=myjar.jar
parameter=myParameter
请确保在运行程序之前,将实际的jar包地址、名字以及传参替换为正确的值,并将配置文件 config.properties 放置在与Java程序相同的目录下
原文地址: https://www.cveoy.top/t/topic/inA6 著作权归作者所有。请勿转载和采集!