【问题标题】:Writing to a properties file does not work写入属性文件不起作用
【发布时间】:2012-11-10 13:30:26
【问题描述】:

我想写入 *.properties 文件。这就是我的代码我如何做到这一点:

    properties = loadProperties("user.properties");//loads the properties file
    properties.setProperty(username, password);
        try {
                properties.store(new FileOutputStream("user.properties"), null);
                System.out.println("Wrote to propteries file!" + username + " " + password);

我没有收到异常,但我也没有将输出写入文件。

这也是我的文件结构:

感谢你的回答!!!

更新

我加载我的属性文件:

    InputStream in = ClassLoader.getSystemResourceAsStream(filename);

我的问题是,如何从特定路径加载它?

这是我的“新”文件结构:

【问题讨论】:

  • 我已经测试了你的代码并且我的属性文件是在我的工作目录中创建的。当然,你的文件结构是错误的。我猜您必须使用文件路径而不是仅使用文件名
  • 当我使用 \\user.properties 之类的路径时,我得到“您无权访问该文件...”

标签: java eclipse file properties


【解决方案1】:

这是我的测试代码:

@Test
public void fileTest() throws FileNotFoundException, IOException {

    File file = null;

    Properties props = new Properties();

    props.setProperty("Hello", "World");

    URL url = Thread.currentThread().getContextClassLoader()
            .getResource("exceptions/user.properties");

    try {
        file = new File(url.toURI().getPath());

        assertTrue(file.exists());
    } catch (URISyntaxException e) {

        e.printStackTrace();
    }

    props.store(new FileOutputStream(file), "OMG, It werks!");

}

它确实在我的 target/classes/exceptions 目录(在 maven/eclipse 项目中)中创建并重写了一个文件,所以我猜它确实有效,但当然这没有在 JAR 文件中测试。

这是文件:

#OMG, It werks!
#Sat Nov 10 08:32:44 CST 2012
Hello=World

另外,检查这个问题:How can i save a file to the class path

所以也许你想做的事情永远不会奏效。

【讨论】:

  • 我正在打印用于检查的 URL,它给我的是:/C:/Users/IBM_ADMIN/workspace/A_Migration_final/bin/common/props_1.dat 但正确的 URL 是 C:\Users \IBM_ADMIN\workspace\A_Migration_final\src\common\props.dat 写在bin文件里,你觉得查询的时候会给出正确的值吗?
猜你喜欢
  • 1970-01-01
  • 2018-01-11
  • 2017-03-30
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2013-04-04
相关资源
最近更新 更多