Skip to main content

Setting Values Basics

The following methods allow you to add, remove, and modify entries and sections in a config file:

Configset(String,Object)set(String,Object,Serializer)set(String,Object,Serializer,String,String,List)set(String,String)remove(String)setSection(String,List)setSection(String,List,Map)removeSection(String)
// Construct the sample config file programmatically
Config config = Config.create("MyConfig.cfg").build()
.set("key1", 1)
.set("key2", true)
.set("key3", new int[]{1,2,3})
.set("key4", new URI("http://foo"))
.set("Section1/key1", 2)
.set("Section1/key2", false)
.set("Section1/key3", new int[]{4,5,6})
.set("Section1/key4", new URI("http://bar"))
.commit();

The method Config.set(String,Object,Serializer,String,String,List) can be used for adding comments and pre-lines to entries, and specifying encoded values.

// Set an encoded value with some comments.
config.set("key1", 1, null, "*", "Same-line comment",
Arrays.asList(
"# Comment 1", "", "# Comment 2"
)
);
# Comment 1
# Comment 2
key1 = 1 # Same-line comment

The last 4 arguments in Config.set(String,Object,Serializer,String,String,List) are optional in that if you pass null, the current value will not be overwritten.

To unset the same-line comment, you should pass in a blank string.

To remove pre-lines, you should pass in an empty list.

Sections can be added with optional pre-lines using the setSection methods:

// Set an encoded value with some comments.
config.setSection("NewSection",
Arrays.asList(
"# Section comment 1", "", "# Section comment 2"
)
);
# Section comment 1
# Section comment 2
[NewSection]

Changes made to the configuration are transactional in nature. They are kept in memory until you call the Config.commit() method. Until then, you still see the modified values when you call any of the getters but the modified values exist only in memory.

Changes can be rolled back using the Config.rollback() method.