In a java application, I am using .properties file to access application related config properties.
For eg.
AppConfig.properties the contents of which are say,
settings.user1.name=userone
settings.user2.name=usertwo
settings.user1.password=Passwrd1!
settings.user2.password=Passwrd2!
I am accesing these properties through a java file - AppConfiguration.java like
private final Properties properties = new Properties();
public AppConfiguration(){
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig.properties"));
}
Now, instead of keeping all the key-value properties in one file, I would like to divide them in few files(AppConfig1.properties, AppConfig2.properties, AppConfig3.properties etc.).
I would like to know if it is possible to load these multiple files simultaneously.
My question is not similar to - Multiple .properties files in a Java project
Thank You.
Yes. Simply have multiple load statements.
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig1.properties"));
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig2.properties"));
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig2.properties"));
All the key-value pairs will be available to use using the properties object.
If I understand your question, you have two objectives in mind:
Partition one very large .properties file into several smaller ones where the (key, value) pairs are related.
Ensure that all .properties files are available at the same time, even if you read them simultaneously using threads.
If that's the case, I'd proceed with partitioning the .properties into several files and write a new class that handles the reading of individual .properties files and the merging of all the results into a single Properties instance.
As Properties objects are in fact map, you can use all of their methods, including putAll(...). In your case, it would be useful to load each Property file using a separate Properties object, then merge them in your application properties.
I have 2 solutions for you:
You can have different properties object for different properties files
You can merge them using putAll().
Properties properties1 = new Properties();
properties1.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig1.properties"));
Properties properties2 = new Properties();
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig2.properties"));
Properties merged = new Properties();
merged.putAll(properties1);
merged.putAll(properties2);
Related
I am working on some automation stuff, in which I just want to write the values into the application.properties file as shown below:
project.ids = 01234, 56789, 14587,...
So here, my key(project.ids) will be the same, I just want to append the ids to the previously stored values (shown above). Whenever my service will be called a new project id will be generated so I just want to append or store the value in the property file to the same key(project.ids).
Could anyone help or suggest here how can I achieve this?
Any suggestions around how to write the value to the application.properties file in Java?
I would suggest to use the Environment class of Spring. But it is only used to read properties and not write them.
what you could do is follow this way:
Load the .properties file:
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("application.properties");
prop.load(in);
Get the value as it is of the property
String ids = prop.getProperty("project.ids");
Set the new value
String ids = prop.setProperty("project.ids", ids + ", 12324...");
PS: I wouldn't play around with the .properties file much, it is mostly used for configurations. Try saving your ids in a DB, Spring can be very helpful for that.
I have a properties file that is in my classpath. My requirement is to change some properties in this file based on some inputs I get from arguments. The nature of arguments decide whether I need to change the properties and if yes which properties to change. The problem is that all classpath entries are loaded at the application startup time, so changing from within my application would not have any effect. How do I overcome this problem?
One possible solution I can think of is to not add this properties file in classpath but add after modifications are done. Is it viable? What can be a good solution?
It doesn't matter whether this file is on your classpath or not. It is a file: if you overwrite its contents, it will have changed. There isn't some in-memory copy that magically gets made at startup. This is very different from classes that are loaded in and which might need change at runtime.
Properties files that adhere to the right format can be read into a java.util.Properties object. You could do that, use the object to alter the properties as needed, then write it back out to the file. Check the store and load methods in that class. Mind that if you use the versions that take an Output/InputStream, the encoding is hard-coded. If the file's encoding is anything else than ISO-8859-1, use a method with an appropriate Writer/Reader.
Depends on how your application is deployed. If your properties files is inside a jar, you won't be able to directly change that properties file since its packaged and zipped up in an archive. You can instead as someone else mentioned load those properties into an object, and then store/write out to an external location, probably a URL based location. URL is convenient because it gets you access to virtually any location and it has that nifty openStream() method for loading properties. Your application could then look for the new file on load, and default to the application startup version if it fails to read/load from the new location.
Here is a sample code:
Properties p = new Properties();
File f = new File("file");
InputStream in = new FileInputStream(f);
p.load(in);
p.put("key", "blah");
OutputStream out = new FileOutputStream(f);
// If no comments p.store(writer);
p.store(out, "properties");
You need to first remove that property from the property file and then re-define it. Their is no way to directly modify the properties file.
Below is an example:
Properties pproperties = new Properties();
if (properties.containsKey("key1")) {
properties.remove("key1");
properties.setProperty("key1", "value1");
properties.store(new FileOutputStream("file.properties"), null);
}
How could I search for string in text file in java?
Would it have to be in a text file or could it read a .ini or some other file type
example
sound = off
opengl = on
openal = off
I tried searching for it on google but I couldnt really find anything.
Thanks in advance
It looks like you want to use a Properties file.
You can load one using Properties.load(String path);
If your file is a properties file or an ini file (key = value), you may want to use the Apache Commons Configuration API. It is much better than the Properties class from the JDK.
There are tons of information with those typical of questions.
Here you have two easy examples:
Loading Java Properties Files http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html
How do I load property settings with the Properties class? http://www.jguru.com/faq/view.jsp?EID=581608
In short it is easy to load a file into a Properties object, for example to obtain, in your case, the sound value in a example.properties file:
Properties props = new Properties();
props.load(new FileInputStream("example.properties"));
String isOnOrOff = props.getProperty("sound");
Any default properties file which java can automatcially load?
The short answer is no.
The somewhat longer answer starts with a question itself: What should be configured by this file?
For the logging-API of java (java.util.logging) exists a standard-properties-file to configure it. Other frameworks may as well use standard-configuration files. But that always configure only stuff specific for this framework.
If you want to have persistent configuration, you probably want to use the Preference-API. That allows you to save configuration-data, that stays with the user or the JVM.
You can use your own default properties file. You can do it with just few lines.
There is also built in properties, however, these are no simpler, but they are standard.
IMHO Most of the time a plain Proeprties file is used.
This example from the tutorial. This is a more complex example, you can have just one properties file.
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create application properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
You have to load your properties file yourself or pass arguments at command line.
There is a small library that you can use which will load properties automatically for you: Confucius.
I want to define a property for a working directory(say work.dir=/home/username/working-directory), for my production .properties file, without hard-coding the /home/username.
I want to reference the system property user.home in place on the hard-coded /home/username, to make work.dir more generic.
How do I reference the system property and concatenate it will other user-defined strings in a user-defined .properties?
Note: I don't want to access the user.home property in my java code, but from the .properties that I have defined. I want to be able to replace the value of the work.dir with different value for both my production and development(JUnit tests for example).
Get the property from the file, then replace supported macros.
String propertyValue = System.getProperty("work.dir");
String userHome = System.getProperty("user.home" );
String evaluatedPropertyValue = propertyValue.replace("$user.home", userHome );
You can manage your properties with Commons Configuration and use Variable Interpolation
If you are familiar with Ant or Maven, you have most certainly already encountered the variables (like ${token}) that are automatically expanded when the configuration file is loaded. Commons Configuration supports this feature as well[...]
That would allow a .properties file with
work.dir=${user.home}/working-directory
This feature is not available in java.util.Properties. But many libraries add variable substitution to properties.
Here an example of what you are trying to do using OWNER API library (see paragraph "importing properties"):
public interface SystemPropertiesExample extends Config {
#DefaultValue("Welcome: ${user.name}")
String welcomeString();
#DefaultValue("${TMPDIR}/tempFile.tmp")
File tempFile();
}
SystemPropertiesExample conf =
ConfigFactory.create(SystemPropertiesExample.class, System.getProperties(), System.getenv());
String welcome = conf.welcomeString();
File temp = conf.tempFile();