【发布时间】:2016-03-10 08:43:33
【问题描述】:
我正在尝试创建一个配置文件,以将客户端的用户名和 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 确实存在,因为我可以从中读取数据,但似乎我无法为其创建输出流。这是为什么?先感谢您。
我遇到的问题是我无法从类路径中的文件打开输出流。
【问题讨论】:
-
这个问题比较含糊,因为我觉得答案不是简单的,“不,你不能在classpath中保存文件。”
-
将输出文件写入其他位置,而不使用 ResourceAsStream 加载。试试绝对路径。
标签: java file filenotfoundexception outputstream properties-file