写入属性文件失败

6

我想写入一个*.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);

我没有遇到异常,但我也没有得到写入文件的输出。
这是我的文件结构: enter image description here 感谢您的回答!!!
更新内容: 我使用以下方法加载属性文件:
    InputStream in = ClassLoader.getSystemResourceAsStream(filename);

我的问题是,如何从特定路径加载它?
以下是我的“新”文件结构:

1
我已经测试了你的代码,我的属性文件已经在我的工作目录中创建。当然,根据你的文件结构,这是错误的。我猜想你必须使用文件路径而不仅仅是使用文件名。 - ElderMael
当我使用类似 \user.properties 的路径时,会出现 "您没有访问该文件的权限..." 的提示。 - maximus
1个回答

4

这是我的测试代码:

@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

此外,请查看这个问题:如何将文件保存到类路径。所以也许您想要做的事情永远不会起作用。

我正在打印用于检查的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文件,您认为在查询时它会给出正确的值吗? - The_Lost_Avatar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接