You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Jar包文件读写异常:IDE、终端运行正常但双击打开失效

问题产生原因
  • Mac系统下终端运行Jar时,默认工作目录为当前登录用户的home目录/Users/me/,你使用相对文件名创建文件时,程序对该目录有读写权限,所以运行正常。
  • 双击运行Jar时,系统为Java进程分配的默认工作目录为根目录/或系统临时目录,普通用户对这类目录没有写入权限,会触发IO异常,导致文件创建、读写失败。
  • 本质问题是你的代码使用了相对路径读写文件,文件存储位置完全依赖进程运行时的工作目录,不同启动方式下工作目录不一致,稳定性差。
修复方案

方案1:固定存储到用户home目录(最稳妥,兼容所有启动方式)

所有普通用户对自己的home目录都有读写权限,直接通过系统属性获取home目录拼接文件路径即可,修改代码如下:

public class FileWriteRead {

    private String fileName;
    private File saveFile;
    private static String data = "";

    public FileWriteRead(String fileName) {
        this.fileName = fileName;
        createFile();
        readFile();
    }

    public final String getData() {
        return data;
    }

    private final boolean createFile() {
        try {
            // 核心修改:拼接用户home目录作为文件存储根路径
            saveFile = new File(System.getProperty("user.home"), fileName);
            if (saveFile.createNewFile()) {
                System.out.println("File " + saveFile.getAbsolutePath() + " created");
                return true;
            } else {
                System.out.println("File " + saveFile.getAbsolutePath() + " already exists");
                return false;
            }
        }catch(IOException e){
            System.out.println("Error creating file");
            // 新增:打印异常栈方便排查具体问题
            e.printStackTrace();
            return false;
        }
    }

    public final boolean writeToFile(String info){
        try{
            // 核心修改:直接使用File对象写文件,避免路径不一致
            FileWriter writer = new FileWriter(saveFile);
            writer.write(info + data );
            writer.close();
            System.out.println("file write successful, path: " + saveFile.getAbsolutePath());

        }catch(IOException e){
            System.out.println("an error occurred");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private final String readFile() {
        try {
            Scanner fileReader = new Scanner(saveFile);
            while(fileReader.hasNextLine()){
                data += fileReader.nextLine();
            }
            System.out.println("File reader created");
            fileReader.close();
            return data;
        }catch(Exception e){
            System.out.println("Read file failed");
            e.printStackTrace();
            return data;
        }
    }
}

方案2:存储到Jar包所在目录(适合配置文件和Jar放一起的场景)

如果需要文件和Jar包同目录存储,可通过以下代码获取Jar包所在路径拼接文件名:

// 获取Jar包所在目录
String jarPath = new File(FileWriteRead.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
// 拼接文件名
saveFile = new File(jarPath, fileName);

内容的提问来源于stack exchange,提问作者user17236595

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 19:36:02