有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java写入属性文件不起作用

我想写进一个*。属性文件。这是我的代码,我是如何做到这一点的:

    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);

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

以下是我的“新”文件结构:

enter image description here


共 (1) 个答案

  1. # 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

    所以也许你想做的事永远不会成功