jar包同目录生成文件实现方式
作者:cmdch2017
文章介绍了如何在Windows环境下将Java程序打包成jar文件,并在Linux环境下运行时生成JSON文件,关键点是确保生成的JSON文件与jar包在同一目录下,而不是当前工作目录(pwd)
jar包同目录生成文件
windows的java程序
打包成jar包,放到linux下运行,执行在jar包同目录下生成json文件,但是注意比如我执行
java -jar /path/to/testapikey/canon2-0.0.1-SNAPSHOT.jar
这个时候你的json文件
要和jar包同一位置,而不是当前pwd的路径
package com.example.canon2;
import java.io.File;
import java.net.URL;
import java.security.CodeSource;
public class JsonFilePathUtil {
public static File getJsonFileInJarDir(String jsonFileName) throws Exception {
CodeSource codeSource = JsonFilePathUtil.class.getProtectionDomain().getCodeSource();
if (codeSource != null) {
URL location = codeSource.getLocation();
if (location != null) {
String urlStr = location.toString();
// 处理 jar:file:/path/to/your.jar!/ 这种格式
if (urlStr.startsWith("jar:")) {
urlStr = urlStr.substring(4, urlStr.indexOf("!"));
}
if (urlStr.startsWith("file:")) {
File jarFile = new File(new URL(urlStr).toURI());
File jarDir = jarFile.isFile() ? jarFile.getParentFile() : jarFile;
if (jarDir != null) {
return new File(jarDir, jsonFileName);
}
}
}
}
// fallback: 当前工作目录
return new File(jsonFileName);
}
public static void main(String[] args) throws Exception {
File jsonFile = getJsonFileInJarDir("result.json");
System.out.println("json file path: " + jsonFile.getAbsolutePath());
// 这里可以继续写入 json 文件
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
