Properties file format in java

How to personally format a properties file in java?

I’m using properties class from java to save some configuration for my application. It’s the first time I’m using properties so please be gentle with me 🙂 I can insert and retrieve data from the properties, no problem, but I want to insert the data as something like: Properties file:

#Header generated by java ~ this is fine, I don't care #Server 1 configuration url=192.168.1.1 port=6546 username=max password=123 #Server 2 configuration url=192.168.2.1 port=6454 username:dude password:123 #And so on. 
public void setProp(String host, String port, String user, String pass, String host2, String port2, String user2, String pass2) < try< prop.setProperty("host", host); prop.setProperty("port", porto); prop.setProperty("username", user); prop.setProperty("password", pass); prop.setProperty("host2", host2); prop.setProperty("port2", porto2); prop.setProperty("username2", user2); prop.setProperty("password2", pass2); config.store(new FileOutputStream("configuration.properties"), "Server 1 Configuration"); >catch (Exception e) < JOptionPane.showMessageDialog(null,"Error: "+e.getMessage()); >> 
#Wed Apr 03 14:03:57 BST 2013 server1.url=192.168.1.1 server1.port=80 server2.password=qqq server1.user=root server2.port=88 server2.user=dude server1.pass=123 server2.url=192.168.2.1 
#Wed Apr 03 14:03:57 BST 2013 #Server 1 details server1.url=192.168.1.1 server1.port=80 server1.user=root server1.pass=123 #Server 2 details: server2.password=qqq server2.port=88 server2.user=dude server2.url=192.168.2.1 

I dont even care if the order is not right (like password above url and under port, etc) I just need them to be grouped by, as they are in my example now.

Читайте также:  Php бесконечное время выполнения скрипта

Источник

Getting Started with Java Properties

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

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.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

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:

Источник

Оцените статью