2017-06-09 53 views
0

通过getResourcestream成功访问属性文件并使用fileinputstream读取。现在我需要在添加新属性后覆盖同一个文件获取项目src中文件的路径并将其传递到fileoutputstream进行覆盖

问题:卡住获​​取fileoutputstream覆盖所需的相同文件的路径。

属性文件在src/main/resources中。,并试图从的src/main/JAVA/COM /网页更新/ 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) {} } 
    } 
+1

为什么不能将资源作为流获取,只需获取资源URL即可。然后,您可以读取和写入该URL。 'URL url = getClass()。getResource(“/ dme.properties”);' –

+1

不要尝试写入类路径资源。它可以在你开发IDE的时候工作,但是当你从一个.jar运行时,它是不可能的。将新的属性写入用户主目录下的新文件。还*永远*写一个空的catch块。至少,打印堆栈跟踪。 – VGR

+0

我想在战争文件中有一个全局设置,可以由不同的用户进行更改。除了数据库方法之外,没有办法通过属性文件来完成吗? @VGR –

回答

0

不但得不到InputStream的,你可以得到的资源URL并用它来读取和文件写入从src/main/resources

Properties properties = new Properties(); 
File file = new File(this.getClass().getResource("/dme.properties").toURI()); 
try (InputStream is = new FileInputStream(file)) { 
    properties.load(is); 
} 
properties.setProperty("a", "b"); 
try (OutputStream os = new FileOutputStream(file)) { 
    properties.store(os, null); 
} 
+0

这是错误的。 URL.getFile()*不会将URL转换为文件名。它仅仅返回URL的路径和查询部分。 (名称'getFile'是由于Java 1.0发布时返回的URL的性质造成的。)如果原始文件名包含空格或URL中非法的任何其他字符,则结果将不是现有文件名。另外,从.jar文件运行时,无法将资源URL转换为文件。 – VGR

+0

@VGR - 感谢您的信息。我已更新为使用正确的“文件”。另外,我不确定OP如何使用这些代码,所以如果他们使用.jar,我明白你的观点并不适用。我只是回答他们最初的问题。 –