How to update a commented out property in Java? - 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.

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}

correct way to read properties file

I am having trouble finding out the right way to load a properties file.
The structure is : Inside src/com.training , I have my class and the properties file as well. I have to read it using the absolute path as shown in the code below to get it to work:
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream("D:/Dev/workspace/Training/src/com/training/consolemessages.properties");
prop.load(input);
System.out.print(prop.getProperty("INITIAL_MESSAGE"));
How can I use the relative path to work in this code for accessing the properties file. The properties file and the class which is accessing are both at the same level '/src/com.training'
You could put your properties files into src/resources folder, and fetch them on classpath.
You could do something like this:
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
System.out.println(bundle.getString("INITIAL_MESSAGE"));
When using ResourceBundle, Locale support is also easy to implement, should you need to have language specific properties.

Modifying Property File [duplicate]

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();

Java - Properties failing to load, but storing properly

I need a configuration file (Properties) for this project I'm working on.
The issue is that the Properties instance fails to load from the file (no exceptions, no visible problems) although it can store properly.
Because I have a defaults HashMap, any property that doesn't exist has it's default value placed in the Properties instance, which then stores everything, so that new properties are seamlessly added when the production server is updated.
I've been tracking this bug for hours, and I can't fix it. I've read dozens of questions here on StackOverflow as well as code examples on other sites. Nothing helped.
The one reason I haven't dropped it already and used the DB instead is that the JDBC driver URL, user and password are stored in that file as well. Notice that the file is being read and written to the hard drive.
Since the defaults system puts stuff in place, even if the file doesn't exist when I try to read, after it's saved it appears, but the next run still won't read anything. I noticed the bug after I changed a setting, and checked the file after a few runs, and to my shock, all values were default.
What's currently happening is the following:
1) No matter if the file is there or not, Properties will not load anything.
2) Since there's nothing in the Properties instance, it is filled with defaults.
3) The instance will now save, overwriting the file with the default values.
Here's all the relevant code:
private static Properties getConfig(){
Properties properties = new Properties();
File cfgFile = new File("data/titallus.properties");
try{
if(cfgFile.createNewFile()){
System.out.println("Config file not found. A default config file will be created automatically.");
}
FileReader reader = new FileReader(cfgFile);
FileWriter writer = new FileWriter(cfgFile);
properties.load(reader);
reader.close();
System.out.println(properties); // Debug, always prints '{}'
for(String k : defaults.keySet()){
if(!properties.containsKey(k)){
properties.setProperty(k, defaults.get(k));
}
}
properties.store(writer, "Titallus Configuration File");
writer.close();
}catch(Exception e){
e.printStackTrace();
System.exit(-1);
}
return properties;
}
I have tried everything I could think of, to no avail.
I also have a Properties subclass for multi-language support, which works just fine.
Does anyone have any idea how to fix this, or at least, another approach to this?
FileWriter writer = new FileWriter(cfgFile);
will be erasing your file before you read from it.
You create a FileWriter for the file before you load the file, which clears the existing data.

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