无法从 java 属性文件中删除密钥

Cannot delete the key from java properties file

我读取了一个属性文件,使用 remove() 从中删除了一个密钥,在这一步之前一切正常。但是,当我尝试使用 store() 将属性保存到文件中时。它不会从属性文件中删除密钥。

这是我的代码:

Properties props = new Properties();
try (InputStream in = Files.newInputStream(Paths.get("/myFolder/myFile.properties"))){
    props.load(in);
}catch(NoSuchFileException e){
    // file not found, continue with empty Properties
}
props.remove("someKeyToDelete");

try (OutputStream out = Files.newOutputStream(Paths.get("/myFolder/myFile.properties"), StandardOpenOption.CREATE)){
    props.store(out, null);
}

这是在里面 myFile.properties:

someKeyToDelete=123

另外,如果我 运行 这个文件的代码:

key1.abc=abc
someKeyToDelete=123
key1.abc2=abc2

我得到了这个结果!!:

key1.abc=abc
key1.abc2=abc2
123
key1.abc2=abc2

只需 运行 您的代码和您的属性文件。更具体地说:

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Properties;

public class Main {
    public static void main(String ... args) throws Exception {
        Properties props = new Properties();
        try (InputStream in = Files.newInputStream(Paths.get("myFile.properties"))){
            props.load(in);
        }catch(NoSuchFileException e){
            // file not found, continue with empty Properties
        }
        props.remove("someKeyToDelete");

        try (OutputStream out = Files.newOutputStream(Paths.get("myFile.properties"), StandardOpenOption.CREATE)){
            props.store(out, null);
        }
    }
}

...它完全按照预期工作,没有任何问题。 注意:使用 Oracle JDK 8

编辑:可能是文件权限或并发问题。 (我无法重现问题)

使用StandardOpenOption.TRUNCATE_EXISTING代替StandardOpenOption.CREATE

来自文档

If the file already exists and it is opened for WRITE access, then its length is truncated to 0. This option is ignored if the file is opened only for READ access.

我改成了TRUNCATE_EXISTING

    try (OutputStream out = Files.newOutputStream(Paths.get("props2.properties"), StandardOpenOption.TRUNCATE_EXISTING)) {
        props.store(out, null);
    }

它按预期创建了属性文件

#Tue Nov 29 22:39:04 IST 2016
key1.abc=abc
key1.abc2=abc2

在 Ubuntu + Java8 上试过,有效

Linux ubuntu 3.19.0-25-generic #26~14.04.1-Ubuntu SMP Fri Jul 24 21:16:20 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux