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.

:)

No comments:

Post a Comment