Quickly saving the program preferences in Java

Many of us just need a quick way of storing some preferences on a given program. Writing files with settings is one way, writing these things on a database is another.

What I needed was something as simple as storing the last used folder on the "Open file" dialog of a Java based program. The idea is making life for end-users (and myself) whenever trying to open the same file and avoid the need of navigating a long extension of folders just to get there.

This is what I use in Java:

Start by declaring the prefs object, where "Custom.class" should be replaced by a valid class:
Preferences prefs = Preferences.userNodeForPackage(Custom.class);

And that's it, no more fuzz.

How can you use this later? Look below.


Example to read a string:
String lastUsedDir = prefs.get("LastUsedDir", "");

Example to write a string:
prefs.put("LastUsedDir", file.getParent());


So, if you're using Windows then these settings get written in the Windows Registry. If you're using Linux or Mac OS, they are written on a preferences text file on disk. What matters is that you don't need to worry any more about these details. Quick and simple solution achieved.

:)

The wonders of JAXB

I never enjoyed XML.

There is nothing in it that would make like more of XML to store settings than for example an old fashioned INI file. It is simple, anyone can read and edit.

They say XML is readable and editable with a text editor, I don't share the same thought. I've used XML across the years for a myriad of stuff but the fashion never got to my taste nor convinced me much - until today.

I had a problem. Wanted to save objects from a running program onto the disk. I don't want to use Hibernate nor go into the trouble of setting up a database. I want something simple, something that I can just code in a few lines and keep performance at best peaks.

And here we go: Try JAXB using this example -> http://www.vogella.com/articles/JAXB/article.html

It is simple. When I mean simple, I mean as simple as creating a class, adding up the setters and getters for the variables that you want store and add one annotation. After this, two or three more lines wherever you want to make use of this information: brilliant!

Works great, works fast. I'm still a die-hard fan of INI style files to keep settings but I now use XML to store complex objects in a simple fashion.

Great stuff.