Which method I can use in Java for configuration file? - java

Which method I can use in Java for configuration files, to read and write specific lines and strings? For example (config.ini):
mysql_host: localhost
mysql_user: user
or
mysql_host = localhost
mysql_user = user

You can use ini4j library.
Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
And then you can go ahead fetch nodes with prefs.node("mysql_host").

Have a look at Java Properties:
Properties are configuration values managed as key/value pairs. In
each pair, the key and value are both String values. The key
identifies, and is used to retrieve, the value, much as a variable
name is used to retrieve the variable's value. For example, an
application capable of downloading files might use a property named
"download.lastDirectory" to keep track of the directory used for the
last download.
To manage properties, create instances of java.util.Properties. This
class provides methods for the following:
loading key/value pairs into a Properties object from a stream,
retrieving a value from its key,
listing the keys and their values,
enumerating over the keys,
and saving the properties to a stream.
You can load properties files with
Properties applicationProps = new Properties();
try (FileInputStream in = new FileInputStream("appProperties")) {
applicationProps.load(in);
}
and store them with
try (FileOutputStream out = new FileOutputStream("appProperties")) {
applicationProps.store(out, "---No Comment---");
}

Related

How can I modify a particular line in a file without deleting the existing data using Java?

I need to change the values in a file which has more than 30 lines and each line has a data like:
ENABLE_TLS=true
PSWD_MIN_LENGTH=8
Here, let us consider this as a key and value pair, and I needed to change only the value for the 2nd line alone, without deleting the 1st line. Can someone help me how can I do this??
I have tried bufferedwriter, but it is replacing all the lines.
My expectation is:
I need to modify only a particular key's value and the remaining lines should not get deleted
Your description of the data sounds like Java Properties. If you are certain that all the data in that file takes the form key=value you could read it in as a Properties object, update the value for the key in question, and write it back to the file.
Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream("/path/to/file")) {
properties.load(inputStream);
}
properties.put("PSWD_MIN_LENGTH", 12);
try (FileOutputStream outputStream = new FileOutputStream("/path/to/file")) {
properties.store(outputStream, null);
}
BEWARE: there is no guarantee that the order of the key/value entries in the file will be maintained (they probably won't). If you are looking for a Properties implementation that will maintain the order, maybe this SO answer will do the trick (UNTESTED!) How maintain the order of keys in Java properties file?

Read text file using java

I have a text file contain two data in two line
admin
temp123
I want to read the text file and store this text to two string for further use.
like,
String username = "admin";
String password = "temp123";
Can any one help me?
Simple google search would have done the job. Check these link:
- https://www.geeksforgeeks.org/different-ways-reading-text-file-java/
- https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
It looks like you are trying to use this for login credentials for something in your application. I would suggest that you look into working with .properties files to get your values, as in the end the java Properties class will handle reading the file and iterating through the key, value pairs it contains.
Example text file:
username=myUser
password=myC0mpLicat3dPa$$W0rd
Java Code:
Properties prop = new Properties();
prop.load(new FileInputStream("myTextFileHere.properties"));
String username = prop.getProperty("username"); // assigned value of "myUser"
String password = prop.getProperty("password"); // assigned value of "myC0mpLicat3dPa$$W0rd"
This will be much simpler than iterating the file, and I imagine more efficient when you decide to work with reading more than two variables in the future.

JAVA Rewrite/store only specified key value of properties

Let say i have property file test.properties.
There are already defined some key/values pairs e.g:
key1=value1
key2=value2
key3=value3
I change in memory some value of these properties (let say only one key's value). I would like to store changes into property file, but to store really only changed key/value => not rewrite whole file.
Is that possible?
Any implementation of some library to I could achieve something like that?
String fileName = "C:\\test\\test.txt";
File f = new File(fileName);
InputStream is = new FileInputStream(f);
Properties p = new Properties();
p.load(is);
p.setProperty("key3","value4");
OutputStream os = new FileOutputStream(f);
p.store(os,"comments");
But I think this will overwrite the entire properties file.
Look at java.util.prefs.Preferences
EDIT:
This is a Java utility class that does what you seem to want -- store key/value pairs (only strings as keys) without having to (re)write an entire file of them to change one value. Java has implemented them with system-dependent backing so they're portable.

Reading Java property groups from a file

Is it possible to read different property groups from a Java file, without manual processing?
By "manual" I mean reading the file line by line, detecting where the start of a property group is and then extracting the corresponding key-value pairs. In practice, this means reinventing (most of) the wheel that the Properties.load() method constitutes.
Essentially, what I am looking for is an easy way of reading, from a single file, multiple groups of properties, with each group being identifiable, so that it can be loaded in its own Java Properties object.
I you want to use java.util.Properties you can use prefixes. In .properties file:
group1.key1=valgroup1key1
group2.key1=valgroup2key1
group2.key2=valgroup2key2
and read them like this:
class PrefixedProperty extends Properties {
public String getProperty(String group, String key) {
return getProperty(group + '.' + key);
}
}
and using:
/* loading, initialization like for java.util.Properties */
String val = prefixedProperty.getProperty("group1", "key1");
You can also use ini4j with windows ini files.
Another, better way is using own, custom structured file (for example XML).

storing and retrieving a list of systems, ips, and usernames

I have a properties file which currently contains system names and ip addresses. What would be the best way for me to store usernames with it as well. Can you use more then one element or key in a properties file? Thanks for any help and suggestions.
Create a class that has the fields you require along with the relevant getters and setters. Then you can set the fields to hold whatever you need and add these objects to your map as the value, e.g.:
public class SystemInfo {
private String systemName;
private String ipAddress;
private String username;
public SystemInfo() {
// do whatever
}
public void setSystemName(String name) {
this.systemName = name;
}
// etc.
}
Then you can create an instance of this, set the information required and store it in your map using whichever field you want as the key (or use some other data structure to store them), e.g.
SystemInfo system1 = new SystemInfo();
system1.setSystemName("The Name");
// etc.
Map<String, SystemInfo> systemMap = new HashMap<String, SystemInfo>();
systemMap.put(system1.getSystemName(), system1);
Are the usernames associated with particular systems?
If so you could just create two properties for each system. One could have a key "(system)_address" and the other "(system)_username"
This is assuming there's only one username per system
1.
system1.ip=10.100.151.1
system1.username=John
2.
Use database instead of properties file.
A Java .properties file is just a text file with key/value pairs in the form "key=value" or "key:value" and represented in Java as a Properties object which is a subclass of Hashtable. While you can store/load the file to XML, it is often much easier to use the default "key=value" form. The keys should be unique, and the values should not contain the delimiter ('=' or ':') unless escaped with a '\'. That said you can add whatever information to the file you want. For more detailed information, check out the API doc: http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.Reader%29. You can use as many keys as desired, as long as they are unique. Depending on the problem you are trying to solve, there may be a better approach.

Categories

Resources