【问题标题】:Delete key and value from a property file?从属性文件中删除键和值?
【发布时间】:2011-05-12 15:59:17
【问题描述】:

我想删除存储在属性文件中的键和值。我该怎么做????

【问题讨论】:

    标签: java properties properties-file


    【解决方案1】:
    public class SolutionHash {
        public static void main(String[] args) throws FileNotFoundException,IOException {
            FileReader reader = new FileReader("student.properties");
            Properties properties = new Properties();
            properties.load(reader);
            // System.out.println(properties);
            Enumeration e = properties.propertyNames();
            while(e.hasMoreElements()){
                String key = (String)e.nextElement();
                if(key.equals("dept"))
                    properties.remove(key);
                else
                    System.out.println(key+"="+properties.getProperty(key));
            }
            // System.out.println(properties);
        }   
    }
    
    OUTPUT:
    name=kasinaat
    class=b
    

    在这里您可以看到我可以使用 remove() 方法删除键值对。

    但是 remove() 方法是 HashTable 对象的一部分。
    它也可以在属性中使用,因为属性是 HashTable 的子类

    【讨论】:

      【解决方案2】:

      首先使用java.util.Properties API load()

      Properties properties = new Properties();
      properties.load(reader);
      

      那么就可以使用remove()方法了。

      properties.remove(key);
      

      最后是store() 到文件中。

      properties.store(writer, null);
      

      另见:

      【讨论】:

      • 仅当密钥存储在哈希表中时才用于删除密钥...我试过它不起作用........:(
      • 你是否按照通常的 Java IO 方式关闭了Writer
      • 他们有办法在 ant 中做到这一点吗?
      • 如果我不使用属性而是使用propertiesConfiguration来加载文件怎么办?
      猜你喜欢
      • 2013-02-20
      • 2018-07-21
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2021-08-15
      • 2023-04-06
      相关资源
      最近更新 更多