Modifying Property File [duplicate] - java

This question already has answers here:
How to use Java property files?
(17 answers)
Java - Properties: Add new keys to properties file in run time?
(1 answer)
Closed 8 years ago.
I have a property file having different data. I need to update the value of a property. How can achieve this using Java?
My property file contains:
# Module Password for Installer
MODULE_PASSWORD=Mg==
# Modules Selected for Installer
ausphur=yes
einfuhr=no
edec=no
emcs=no
ncts=no
suma=no
eas=no
zollager=no
I need to change yes or no values.

Create a FileOutputStream to the properties file and modify the property by using Properties.setProperty(PROPERTY_NAME,PROPERTY_VALUE) and then call store(out,null) on Properties instance
FileOutputStream out = new FileOutputStream("config.properties");
props.setProperty("ausphur", "no");
props.store(out, null);
out.close();
This will help!
Update:
There is no way to keep your comments back since Properties doesn't know about it. If you use java.util.Properties, it is a subclass of Hashtable which doesn't preserve the order of the keys and values the way they are inserted. What you can do is, you can go for LinkedHashMap collection with your own implementation of Properties datastore. But, you have to read the properties from file yourself and put it in LinkedHashMap. To Note, LinkedHashMap preserves the order in which keys are values are put. so, you can iterate the keyset and update the properties file in the same order back. Thus, the order can be preserved

You could use Properties Java class.
It allows you to handle in a very easy way properties files based on (key, value) pair.
Have a look at http://docs.oracle.com/javase/tutorial/essential/environment/properties.html
In particular:
Saving Properties
The following example writes out the application properties from the previous example using Properties.store. The >default properties don't need to be saved each time because they never change.
FileOutputStream out = new FileOutputStream("appProperties");
applicationProps.store(out, "---No Comment---");
out.close();
The store method needs a stream to write to, as well as a string that it uses as a comment at the top of the output.

Try this.
Properties prop = new Properties();
OutputStream output = null;
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("propertyname", "newValue");
prop.store(output, null);

Use java.util.Properties.
Properties props = new Properties();
FileInputStream fis = new FileInputStream("pathToYourFile");
props.load(fis);
fis.close();
props.setProperty("propName", "propValue");
FileOutputStream fos = new FileOutputStream("pathToYourFile");
props.store(fos, "Your comments");
fos.close();

Related

Using properties file in Java: copy key value and assign it to another key

is it possible to achieve below scenario using properties file in Java. Thanks a lot for any feedback.
Assume I have a settings.properties file which includes,
my.name=${name}
his.name=hisNameIs${name}
In my code,
InputStream input = new FileInputStream("path/settings.properties");
Properties prop = new Properties();
prop.setProperty("my.name", "John");
prop.load(input);
String output= prop.getProperty(his.name);
System.out.println(output);
Expected Results:
hisNameIsJohn
The Apache Commons Configuration Project has an implementation capable of doing variable interpolation.
Read the section named Variable Interpolation
application.name = Killer App
application.version = 1.6.2
application.title = ${application.name} ${application.version}
You would need this third-party library in your class path, but on the other hand you will not have to worry about writing yet another implementation for this :)
You might like to read the Properties How To as well.
Posting the solution using org.apache.commons.configuration.PropertiesConfiguration
PropertiesConfiguration prop = new PropertiesConfiguration(new File("path/settings.properties"));
prop.addProperty("name", "John");
prop.getProperty(his.name);
In, "settings.properties" file.
his.name=hisNameIs${name}

Properties file resets when adding or updating value (Java)

I'm storing user data (nothing important, just user ID and xp amount/level) in a properties file. When using prop.store(output, comment) it resets the file completely and then stores the added data. How can I add data without it resetting the entire file?
Each time you use the store() method, it removes the old data and writes the new data.
To prevent this from happening, you must first load your data and then restore it with new data that you want to add.
This code snippet may help you:
Properties prop = new Properties();
prop.load(new FileInputStream(YOUR_PROPERTIE_FILE));
prop.setProperty(key, value);
prop.store(new FileOutputStream(YOUR_PROPERTIE_FILE), COMMENT);

How to differentiate properties in properties file

my.properties
#db connection
mongoconnection=mongodb://user:password#host:27017/database?maxPoolSize=1
#serial=vehicleID
077C70=47368
077C71=47367
077C72=47366
Properties properties = new Properties();
properties.load(new FileInputStream("my.properties"));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String serialNumber = (String) entry.getKey();
String vehicleId = (String) entry.getValue();
}
In for loop I'm getting 'mongoconnection' as key and its respected value.
I want to differentiate 'db connection' and 'serial=vehicleID'
Properties class provide only flat view of all provided key-value pairs, there is no way to differentiate between blocks.
You could write your own parser for the file you are trying to read
I think you can make a tag to set java environment like this:-Dflag=my. and then you can read different file to get different properties by environment.
You could split your properties in two files (serial.properties, connection.properties)bBecause the properties seems to not have any relation between them. One file for the connection. And the other for the serials. This way, you read the serial properties and do your logic, and when you need the database url you read from the other file.
I normally create a properties file with properties that have something in common. For example, translations properties files have his own properties, database connection properties too. This way is easier to edit and find the properties in the future as the project grow.
Hope this helps.

How to update a commented out property in Java?

My property file has properties like below:
#property1=
property2=asd
Is there a proper way to un comment and change the property1? I was looking at Apache Commons but there seems to be no non-ugly way to do this. The following wont work as the commented out property wont be read in the first place.
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
layout.load(new InputStreamReader(new FileInputStream(new File(filePath))));
config.setProperty("#property1", "new_value");
FileWriter propsFile = new FileWriter(filePath, false);
layout.save(propsFile);
I assume you are looking for a way to do this in code, not with an editor.
If you read in the property file to java.util.Properties, the comments are all lost.
Your best bet is to read the property file into a String and update the string using a regex replace.
String newProperties = properties.replaceAll("^#*\s*property1=", "property1=");
Properties props = new Properties();
props.load(new StringReader(newProperties));
Expanding on what #garnulf said, you want to do config.setProperty("property1", "new_value");
You aren't "uncommenting" the property value, but rather adding the property to your configuration at runtime. The file will not be changed.
Your configuration will not include the commented out property when you first load it (because it is commented out). When you call config.setProperty it will be added to your config.

How to read a metadata file efficiently?

My current project is using a metadata file to set properties without having to compile. Currently I have it set up in this way:
metadata.txt
[property] value <br/>
[property2] value2
File f = new File("metadata.txt");
BufferedReader in = new BufferedReader(new FileReader(f));
String variable1 = "";
String variable2 = "";
Now read this file using a BufferedReader and getting the information in a certain order. Such as:
variable1 = in.readLine();
variable2 = in.readLine();
I was wondering is there a better way to do this without having to read line by line? I was trying to think of using a loop but I'm not sure how that would work out since I want to set different String variables to each property.
Also I'm not using a GUI in this program so that is the reason why I'm editing the data raw.
Rather use the java.util.Properties API. It's designed exactly for this purpose.
Create a filename.properties file with key=value entries separated by newlines:
key1=value1
key2=value2
key3=value3
Put the file in the classpath (or add its path to the classpath) and load it as follows:
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties"));
Then you can obtain values by key as follows:
String key1 = properties.getProperty("key1"); // returns value1
See also:
Properties tutorial
I'm not sure this is an answer to this question.
You can use java.util.Properties and its methods to save or load properties from the file. You metadata file looks like a property file, if you don't target doing something special.

Categories