Setting java properties in code

Getting Started with Java Properties

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

Most Java application need to use properties at some point, generally to store simple parameters as key-value pairs, outside of compiled code.

And so the language has first class support for properties – the java.util.Properties – a utility class designed for handling this type of configuration files.

That’s what we’ll focus on in this article.

2. Loading Properties

2.1. From Properties Files

Let’s start with an example for loading key-value pairs from properties files; we’re loading two files we have available on our classpath:

version=1.0 name=TestApp date=2016-11-12
c1=files c2=images c3=videos

Notice that although the properties files are recommended to use “.properties“, the suffix, it’s not necessary.

We can now load them very simply into a Properties instance:

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); String appConfigPath = rootPath + "app.properties"; String catalogConfigPath = rootPath + "catalog"; Properties appProps = new Properties(); appProps.load(new FileInputStream(appConfigPath)); Properties catalogProps = new Properties(); catalogProps.load(new FileInputStream(catalogConfigPath)); String appVersion = appProps.getProperty("version"); assertEquals("1.0", appVersion); assertEquals("files", catalogProps.getProperty("c1"));

As long as a file’s content meet properties file format requirements, it can be parsed correctly by Properties class. Here are more details for Property file format.

2.2. Load From XML Files

Besides properties files, Properties class can also load XML files which conform to the specific DTD specifications.

Here is an example for loading key-value pairs from an XML file – icons.xml:

   xml example icon1.jpg icon2.jpg icon3.jpg 
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); String iconConfigPath = rootPath + "icons.xml"; Properties iconProps = new Properties(); iconProps.loadFromXML(new FileInputStream(iconConfigPath)); assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));

3. Get Properties

We can use getProperty(String key) and getProperty(String key, String defaultValue) to get value by its key.

If the key-value pair exists, the two methods will both return the corresponding value. But if there is no such key-value pair, the former will return null, and the latter will return defaultValue instead.

String appVersion = appProps.getProperty("version"); String appName = appProps.getProperty("name", "defaultName"); String appGroup = appProps.getProperty("group", "baeldung"); String appDownloadAddr = appProps.getProperty("downloadAddr"); assertEquals("1.0", appVersion); assertEquals("TestApp", appName); assertEquals("baeldung", appGroup); assertNull(appDownloadAddr);

Note that although Properties class inherits get() method from Hashtable class, I wouldn’t recommend you use it to get value. Because its get() method will return an Object value which can only be cast to String and the getProperty() method already handles the raw Object value properly for you.

The code below will throw an Exception:

float appVerFloat = (float) appProps.get("version");

4. Set Properties

We can use setProperty() method to update an existed key-value pair or add a new key-value pair.

appProps.setProperty("name", "NewAppName"); // update an old value appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); // add new key-value pair String newAppName = appProps.getProperty("name"); assertEquals("NewAppName", newAppName); String newAppDownloadAddr = appProps.getProperty("downloadAddr"); assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);

Note that although Properties class inherits put() method and putAll() method from Hashtable class, I wouldn’t recommend you use them for the same reason as for get() method: only String values can be used in Properties.

The code below will not work as you wish, when you use getProperty() to get its value, it will return null:

5. Remove Properties

If you want to remove a key-value pair, you can use remove() method.

String versionBeforeRemoval = appProps.getProperty("version"); assertEquals("1.0", versionBeforeRemoval); appProps.remove("version"); String versionAfterRemoval = appProps.getProperty("version"); assertNull(versionAfterRemoval);

6. Store

6.1. Store to Properties Files

Properties class provides a store() method to output key-value pairs.

String newAppConfigPropertiesFile = rootPath + "newApp.properties"; appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");

The second parameter is for comment. If you don’t want to write any comment, simply use null for it.

6.2. Store to XML Files

Properties class also provides a storeToXML() method to output key-value pairs in XML format.

String newAppConfigXmlFile = rootPath + "newApp.xml"; appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");

The second parameter is as same as it in the store() method.

7. Other Common Operations

Properties class also provides some other methods to operate the properties.

appProps.list(System.out); // list all key-value pairs Enumeration valueEnumeration = appProps.elements(); while (valueEnumeration.hasMoreElements()) < System.out.println(valueEnumeration.nextElement()); >Enumeration keyEnumeration = appProps.keys(); while (keyEnumeration.hasMoreElements()) < System.out.println(keyEnumeration.nextElement()); >int size = appProps.size(); assertEquals(3, size);

8. Default Property List

A Properties object can contain another Properties object as its default property list. The default property list will be searched if the property key is not found in the original one.

Besides “app.properties“, we have another file – “default.properties” – on our classpath:

site=www.google.com name=DefaultAppName topic=Properties category=core-java
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); String defaultConfigPath = rootPath + "default.properties"; Properties defaultProps = new Properties(); defaultProps.load(new FileInputStream(defaultConfigPath)); String appConfigPath = rootPath + "app.properties"; Properties appProps = new Properties(defaultProps); appProps.load(new FileInputStream(appConfigPath)); assertEquals("1.0", appVersion); assertEquals("TestApp", appName); assertEquals("www.google.com", defaultSite);

9. Properties and Encoding

By default, properties files are expected to be ISO-8859-1 (Latin-1) encoded, so properties with characters outside of the ISO-8859-1 shouldn’t generally be used.

We can work around that limitation with the help of tools such as the JDK native2ascii tool or explicit encodings on files, if necessary.

For XML files, the loadFromXML() method and the storeToXML() method use UTF-8 character encoding by default.

However, when reading an XML file encoded differently, we can specify that in the DOCTYPE declaration; writing is also flexible enough – we can specify the encoding in a third parameter of the storeToXML() API.

10. Conclusion

In this article, we have discussed basic Properties class usage, including how to use Properties load and store key-value pairs in both properties and XML format, how to operate key-value pairs in a Properties object, such as retrieve values, update values, get its size, and how to use a default list for a Properties object.

The complete source code for the example is available in this GitHub project.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Читайте также:  Beginning python games development
Оцените статью