如何获取包中的所有属性文件并使用 java 更新键值?

How to get all properties files in a package and update the key values using java?

我尝试了很多,但找不到解决方案。

|
|--src/main/resouces
       |
       |-updatePropertiesFile.java
       |-xyz_en_US.properties
       |-xyz_en_AF.properties
       |-xyz_en_AE.properties

这是我的项目结构。

我有一个 updatePropertiesFile class,用于更新所有属性文件的密钥。我有大约 200 个属性文件。

所以我需要的是,我需要编写一种方法来更新所有这些属性文件中的特定键。手动更改不是那么实际。我需要编写一个执行此功能的应用程序。

我试过使用resoucebundle机制。但是使用资源包,我们只能得到一个 属性 文件。我尝试了 ResourceBundle.getBundle(String,Locale)ResourceBundle.getBundle(String) 方法。

我需要遍历这些属性文件并更新密钥。

我的初始问题已解决。

我是这样做的:

File[] files = new File("src/main/resources").listFiles();
    for (File file : files) {
    if (file.getName().endsWith("properties"))  {
     //my logic
    }

但是当我这样做时,我在属性文件中的注释被删除并且顺序被更改。我也想在属性文件中保持键和注释的顺序。

为了保持我尝试使用的顺序:

public static class LinkedProperties extends Properties {
        private final HashSet<Object> keys = new LinkedHashSet<Object>();

        public LinkedProperties() {
        }

        public Iterable<Object> orderedKeys() {
            return Collections.list(keys());
        }

        public Enumeration<Object> keys() {
            return Collections.<Object>enumeration(keys);
        }

        public Object put(Object key, Object value) {
            keys.add(key);
            return super.put(key, value);
        }
    }

但这导致属性文件中的键值对发生了一些变化。添加了一些特殊字符。

请帮我维护评论和秩序

每个 Java IDE 都有一个替换路径功能。 Sublime Text、VS Code 和 Atom 几乎肯定也有。 IntelliJ 的特别好。甚至没有理由编写 Java 代码来执行此操作。否则,就这么简单:

File[] files = new File("src/main/resources").listFiles();
for (File file in files) {
    if (file.getName().endsWith("properties")) {
        //Load and change...
    }
}

此代码遍历给定目录中的所有文件并打开每个 .properties 文件。然后应用更改的值并再次存储文件。

public void changePropertyFilesInFolder(File folder) {
    for(File file : folder.listFiles()) {
        if(file.isRegularFile() && file.getName().endsWith(".properties")) {
            Properties prop = new Properties();
            FileInputStream instream = new FileInputStream(file);
            prop.load(instream);
            instream.close();
            prop.setProperty("foo", "bar"); // change whatever you want here
            FileOutputStream outstream = new FileOutputStream(file);
            prop.store(outstream, "comments go here");
            outstream.close();
        }
    }
}