【问题标题】:Get path of file inside project src and pass it to fileoutputstream for overwriting获取项目 src 中文件的路径并将其传递给 fileoutputstream 进行覆盖
【发布时间】: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


【解决方案1】:

您可以获取资源URL,而不是获取InputStream,并使用它来读取和写入来自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);
}

【讨论】:

  • 这是错误的。 URL.getFile() 将 URL 转换为文件名。它仅返回 URL 的路径和查询部分。 (名称“getFile”是由于 Java 1.0 发布时 URL 的性质。)如果原始文件名包含空格或任何其他在 URL 中非法的字符,则结果将不是现有文件名。此外,从 .jar 文件运行时,无法将资源 URL 转换为文件。
  • @VGR - 感谢您提供信息。我已经更新为使用正确的File。另外,我不确定 OP 将如何使用此代码,因此如果他们从 .jar 中使用它,我理解您对此不起作用的观点。我只是在回答他们最初的问题。
猜你喜欢
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 2019-06-30
相关资源
最近更新 更多