java - 读取/写入 jar 文件内的属性文件

标签 java netbeans windows-8 properties-file

所以我在 4 年后重新开始编写 Java,所以请原谅任何“菜鸟”错误。

我需要一个属性文件,可以在其中为我的应用程序存储一些简单的数据。应用程序数据本身不会驻留在此处,但我将存储信息,例如上次使用的数据存储的文件路径、其他设置等。

我设法连接到与尝试连接到它的类文件位于同一包内的属性文件,我可以读取该文件,但写回该文件时遇到问题。我非常确定我的代码可以正常工作(至少不会引发任何错误),但在 Netbeans 中运行应用程序后,更改不会反射(reflect)在文件本身中。

enter image description here

在上图中,您可以看到相关的 mainProperties.properties 文件以及尝试调用它的类 (prefManagement.java)。因此,考虑到这一点,这是我加载文件的代码:

Properties mainFile = new Properties();
try {

    mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));


} catch (IOException a) {

    System.out.println("Couldn't find/load file!");

}

这有效,我可以检查并确认一个现有 key (defaultXMLPath)。

我要添加到此文件的代码是:

String confirmKey = "defaultXMLPath2";

String propKey = mainFile.getProperty(confirmKey);

if (propKey == null) {

    // Key is not present so enter the key into the properties file
    mainFile.setProperty(confirmKey, "testtest");


    try{

        FileOutputStream fos = new FileOutputStream("mainProperties.properties");
        mainFile.store(fos, "testtest3");
        fos.flush();

    }catch(FileNotFoundException e ){
        System.out.println("Couldn't find/load file3!");
    }catch(IOException b){
        System.out.println("Couldn't find/load file4!");
    }



} else {

    // Throw error saying key already exists
    System.out.println("Key " + confirmKey + " already exists.");

}

正如我上面提到的,一切都运行没有任何错误,我可以尝试添加现有的 key ,它会抛出预期的错误。但是,当尝试添加新的键/值对时,它不会出现在属性文件后记中。为什么?

最佳答案

您不应该尝试写入 jar 文件中存在的"file"。实际上,从技术上讲,jar 文件并不保存文件,而是保存“资源”,并且出于实际目的,它们是只读的。如果您需要读取和写入属性文件,它应该位于 jar 之外。

关于java - 读取/写入 jar 文件内的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61189433/

相关文章:

java - 将 View 从一个 View 组移动到另一个 View 组

java - 如何在Eclipse中调试外部插件?

java - 如何在选择另一个选项之前检查用户是否输入了某些内容?

javascript - 根据源删除图像元素

c++ - Qt 中的 Qwizard 在窗口 8 上不显示完成和取消按钮,相同的代码在 7 上工作

java - `class <T extends A> { }` 和使用 A 的 `class { }` 之间的实际区别是什么?

java - Lucene 和土耳其字符

java - 如何将程序中的变量分配给 Swing 中的图标?

c++ - 如何在 Debug模式下使用 Netbeans 编译 Assimp?

sqlite - 如何在带有 ARM CPU 的 WinRT 设备中部署 SQLite?