如何读写可执行JAR包内的config.properties配置文件
无法直接修改JAR包内的properties文件,正确方案如下
核心结论
JAR是压缩归档文件,运行时处于只读状态,Java不允许对正在运行的JAR包内的文件进行写入操作。你当前代码生成外部config.properties的行为是正常的,但需要调整读取逻辑来统一配置来源。
问题根源
你用installationClass.class.getResourceAsStream("config.properties")读取的是JAR内部的资源文件,而FileWriter("config.properties")会在JAR所在的同级目录生成新文件,两者路径不一致,导致其他类无法读取到修改后的配置。
正确实现方案
1. 配置读取逻辑:优先读取外部配置, fallback到JAR内默认配置
修改读取代码,先检查JAR同级目录的config.properties是否存在,存在则读取该文件;不存在则读取JAR内的默认配置。这样第一次运行使用默认值,后续运行使用修改后的外部配置。
private static Properties loadConfig() { Properties prop = new Properties(); // 获取JAR所在的目录路径 String jarDir = System.getProperty("user.dir"); File externalConfig = new File(jarDir, "config.properties"); // 先尝试读取外部配置 if (externalConfig.exists()) { try (FileInputStream fis = new FileInputStream(externalConfig)) { prop.load(fis); } catch (IOException e) { e.printStackTrace(); } } else { // 外部配置不存在,读取JAR内的默认配置 try (InputStream is = installationClass.class.getResourceAsStream("config.properties")) { if (is != null) { prop.load(is); } } catch (IOException e) { e.printStackTrace(); } } return prop; }
2. 配置写入逻辑:固定写入到JAR同级目录
写入时直接指定JAR同级目录的config.properties路径,确保读取和写入的是同一个文件:
private static void saveConfig(Properties prop, String filePath) { String jarDir = System.getProperty("user.dir"); File externalConfig = new File(jarDir, "config.properties"); try (FileWriter fw = new FileWriter(externalConfig)) { prop.setProperty("Install", "true"); // 用File.separator实现跨平台路径兼容 String fullPath = filePath + File.separator + "Tracking Program" + File.separator + "Text Files"; prop.setProperty("FileLocation", fullPath); prop.store(fw, "Updated installation configuration"); } catch (IOException e) { e.printStackTrace(); } }
额外建议
- 跨平台兼容:尽量使用
File.separator代替硬编码的\\,避免在Linux/Mac系统出现路径错误。 - 配置文件位置:如果不希望配置文件和JAR同级,可以选择用户主目录(
System.getProperty("user.home"))或系统应用数据目录,更符合操作系统的规范。
内容的提问来源于stack exchange,提问作者Blake
相关产品推荐
相关产品推荐

