我正在尝试创建一个配置文件,以在类路径中保存客户端的用户名和ip数据,就像在项目中的资源文件夹中一样。我可以像这样检索属性:
public String getProperty(String property){
String result = null;
try{
InputStream inputStream = this.getClass().getResourceAsStream(filename);
Properties properties = new Properties();
if (inputStream != null){
properties.load(inputStream);
System.out.println(this.getClass().getResource(filename).toString());
}else {
System.out.println("File not found or loaded: "+filename);
}
result = properties.getProperty(property, null);
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
但是我还希望能够设置可以从文件中获取的那些值,因此,为了做到这一点,我使用以下方法:
public void setProperty(String property, String value){
try{
OutputStream out = new FileOutputStream(this.getClass().getResource(filename).getFile());
Properties properties = new Properties();
properties.setProperty(property, value);
properties.store(out, "Optional comment");
out.close();
}catch (Exception e){
System.out.println("Unable to load:"+filename);
e.printStackTrace();
}
}
但是,运行该方法给我以下错误:
java.io.FileNotFoundException: file:/home/andrew/Documents/Programming/Executable-JARs/SchoolClient.jar!/client-config.properties (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at com.andrewlalis.utils.DataSaver.setProperty(DataSaver.java:54)
at com.andrewlalis.MainClient.getNewIp(MainClient.java:173)
at com.andrewlalis.ClientWindow$4.mouseClicked(ClientWindow.java:142)
现在,我已经确认该文件client-config.properties
确实存在,因为我能够从中读取数据,但是似乎无法为其创建输出流。这是为什么?先感谢您。
我的问题是我无法从类路径中的文件打开输出流。
该属性位于您的.jar文件中。因此,您的问题应该是“如何修改当前正在执行的.jar文件的内容”,这不是一个好主意。
这里的主要问题是:
您是否需要坚持这些价值观?
如果您设置的值仅在程序运行时才保持活动状态,那很好-.setProperty(key, value);
一切都很好。
另一方面,如果您希望这些值在应用程序的下一次启动时得以保留,则可能需要考虑Preferences
使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句