it编程 > 游戏开发 > ar

jar包同目录生成文件实现方式

31人参与 2025-11-20 ar

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

您想发表意见!!点此发布评论

推荐阅读

通过DBeaver连接GaussDB数据库的实战案例

11-20

手机Dock栏扩容且不影响任务接续! 华为鸿蒙 HarmonyOS 6.0.0.112再曝新特性

11-20

支持多设备升级与桌面布局优化! 华为鸿蒙HarmonyOS 6.0.0.112版本推送

11-19

华为鸿蒙 HarmonyOS 6.0.0.112 SP12最新适配机型公布

11-19

App可收纳至应用中心! 华为鸿蒙HarmonyOS 6.0.0.112 SP22更新日志曝光

11-18

服务器获取Jar包运行目录实现方式

11-18

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论