加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 写入属性文件不起作用

发布时间:2020-12-14 19:22:29 所属栏目:Java 来源:网络整理
导读:我想写入* .properties文件.多数民众赞成我的代码如何做到这一点: properties = loadProperties("user.properties");//loads the properties file properties.setProperty(username,password); try { properties.store(new FileOutputStream("user.properti

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

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

这也是我的文件结构:

我感谢你的回答!!!

UPDATE

我加载我的属性文件:

    InputStream in = ClassLoader.getSystemResourceAsStream(filename);

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

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

最佳答案
这是我的测试代码:

@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 proyect中),所以我猜它确实有效,但当然没有在JAR文件中测试过.

这是文件:

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读