gpt4 book ai didi

java - Jar 和文件 I/O

转载 作者:行者123 更新时间:2023-11-29 06:16:41 24 4
gpt4 key购买 nike

在我的 Java 项目中,我在文件夹 src/properties 中有一些属性文件。在eclipse中运行应用程序加载和保存文件时用下面的代码是没有问题的:

    // create and load default properties
Properties defaultProps = new Properties();
File file = new File("src/properties/defaultProperties");
if (!file.exists()){
// Create new properties file
...
FileOutputStream out = new FileOutputStream("defaultProperties");
defaultProps.store(out, "---No Comment---");
out.close();
} else {
// Load existing properties file
FileInputStream in = new FileInputStream(file);
defaultProps.load(in);
in.close();
}

但是,当我使用 eclipse 创建一个 Runnable Jar 文件时,属性无法正确加载。保存文件时也会发生同样的情况。我读了一些关于:

InputStream is = getClass().getResourceAsStream(path);

但在这种情况下,如果文件存在,我如何检查输入流?如何正确执行此 I/O 以使其在可执行 Jar 文件中工作?

最佳答案

宁可使用java.util.prefs.Preferences .它类似于 java.util.Properties,不同之处在于它不存储在属性文件中,而是存储在特定于平台的配置管理中。例如,在 Windows 机器上,这就是注册表。

另见:

关于java - Jar 和文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4837235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com