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 文件}
}