How to read a metadata file efficiently? - java

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.

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}

Java Replacing one word in a string from a text file

So i have a confing file here is an example from that file
<STX><ESC>F16<LF>vartest<ETX>
After reading the config file i need to create a new file but in that new file i should replace the "vartest" with an actual string. What would be the easiest way to do this.
I read the file like this
line17 = scan.nextLine();
Write it like this
bufferW.write(line17);
bufferW.newLine();
JDK11 // IntelliJ IDE
Just use String#replace(), this replaces vartest in your line17 string with mynewstring, ofcourse this can be whatever you want:
line17 = line17.replace("vartest", "mynewstring");
// Alternatively using a variable instead
line17 = line17.replace("vartest", myStringVariable);

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.

Loading multiple properties sets from single file for multiple class instances

I have a class of which I need a different instance if one of its attributes changes. These changes are read at runtime from a property file.
I would like to have a single file detailing the properties of all the single instances:
------------
name=Milan
surface=....
------------
name=Naples
surface=....
How can I load each set of properties in a different Property class (maybe creating a Properties[])? Is there a Java built in method to do so?
Should I manually parse it, how could create an InputStream anytime I find the division String among the sets?
ArrayList<Properties> properties = new ArrayList<>();
if( whateverItIs.nextLine() == "----" ){
InputStream limitedInputStream = next-5-lines ;
properties.add(new Properties().load(limitedInputStream));
}
Something like above. And, by the way, any constructor method which directly creates the class from a file?
EDIT: any pointing in the right direction to look it for myself would be fine too.
First of all, read the whole file as a single string. Then use split and StringReader.
String propertiesFile = FileUtils.readFileToString(file, "utf-8");
String[] propertyDivs = propertiesFile.split("----");
ArrayList<Properties> properties = new ArrayList<Properties>();
for (String propertyDiv : propertyDivs) {
properties.add(new Properties().load(new StringReader(propertyDiv)));
}
The example above uses apache commons-io library for file to String one-liner, because Java does not have such a built-in method. However, reading file can be easily implemented using standard Java libraries, see Whole text file to a String in Java

How to replace a line in a text file using Java?

I have a text file with various key value pairs separated with a '--'.
Below is the code I have so far
File file = new File("C:\\StateTestFile.txt");
BufferedWriter out = new BufferedWriter(file.getAbsolutePath());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("content_style")) {
//Write to the line currently reading and save back to the file
}
}
br.close();
out.close();
What I would like to do is read this text file and replace the value of a specific line with something I specify. So id want to find the 'content_style' line and replace 'posh' with 'dirty'.
How can I do this?
simply use:
line = line.replaceAll("posh", "dirty"); // as strings are immutable in java
This can be done in-place on a single file only if you are sure that the string you are replacing is exactly the same length in bytes as the string that replaces it. Otherwise, you can't add or delete characters in a single file, but you can create a new file.
Open the source file for reading.
Open the destination file for writing.
Read each line in the source file, use replaceAll, and write it to the destination file.
Close both files.
Alternate method that preserves the key-value semantics:
Open the source file for reading.
Open the destination file for writing.
Split each line in the source file into a key and value pair. If the key equals "content_style", write the key and "dirty" to the destination file. Otherwise write the key and value.
Close both files.
Finally, delete the old file and rename the new file on top of the old one. If you're going to be doing key-value manipulations often, and you don't want to write out a new file all the time, it might be worth it to use a database. Look for a JDBC driver for SQLite.

Categories