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 文件
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论