Delete key and value from a property file?

旧时模样 提交于 2019-12-19 12:24:40

问题


I want to delete key and value which is stored in a property file. How can i do that????


回答1:


First load() it using the java.util.Properties API.

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

Then you can use the remove() method.

properties.remove(key);

And finally store() it to the file.

properties.store(writer, null);

See also:

  • Properties tutorial



回答2:


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

Here you can see that I could remove a key value pair using remove() method.

However the remove() method is a part of the HashTable object.
It is also available in properties because properties is a subclass of HashTable



来源:https://stackoverflow.com/questions/4225794/delete-key-and-value-from-a-property-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!