【发布时间】:2017-06-09 13:58:40
【问题描述】:
通过 getResourcestream 成功访问属性文件并使用 fileinputstream 读取。现在我需要在添加新属性后覆盖同一个文件
问题:无法获取文件输出流覆盖所需的同一文件的路径。
属性文件位于 src/main/resources. 并尝试从 src/main/java/com/web/my.class
更新 Properties prop = new Properties();
InputStream in = getClass().getClassLoader().getResourceAsStream("dme.properties");
FileOutputStream out = null;
try {
prop.load(in);} // load all old properties
catch (IOException e) {}
finally {try { in.close(); } catch (IOException e) {} }
prop.setProperty("a", "b"); //new property
try {
out = new FileOutputStream("dme.properties");
prop.store(out, null);} //overwrite
catch (IOException e) {}
finally {try {out.close();} catch (IOException e) {} }
}
【问题讨论】:
-
为什么不将资源作为流获取,而只是获取资源 URL。然后,您可以从该 URL 读取和写入。
URL url = getClass().getResource("/dme.properties"); -
不要尝试写入类路径资源。当您在 IDE 中开发时,它可以工作,但是当您从 .jar 运行时,它根本不可能。将您的新属性写入用户主目录下的新文件。另外从不写一个空的catch块。至少,打印堆栈跟踪。
-
我想在war文件中有一个全局设置,可以由不同的用户更改。除了数据库方法之外,有没有办法通过属性文件来完成? @VGR
-
您不能在运行时写入 .war 文件或 .jar 文件。可写数据必须存储在单独的文件、数据库或其他数据存储中。
标签: java properties fileinputstream fileoutputstream