Storing Strings in Properties and Preferences
Problem
You need to store keys and values that are both strings, possibly with persistence across runs of a program. For example: program customization.
Solution
Use a
java.util.Properties
object (or a
java.util.Prefs.Preferences object in JDK 1.4).
Discussion
The Properties class is similar to a
HashMap or Hashtable (it
extends the latter), but with methods defined specifically for string
storage and retrieval and for loading/saving.
Properties objects are used throughout Java, for
everything from setting the platform font names to customizing user
applications into different Locale settings as
part of internationalization and localization. When stored on disk, a
Properties object looks just like a series of
name=value assignments, with optional comments.
Comments are
added when you hand-edit a
Properties file, ignored when the
Properties object reads itself, and lost when you
ask the Properties object to save itself to disk.
Here is an
example of a Properties file that could be used to
internationalize the menus in
a GUI-based program:
# Default properties for MenuIntl program.title=Demonstrate I18N (MenuIntl) program.message=Welcome to an English-localized Java Program # # The File Menu # file.label=File Menu file.new.label=New File file.new.key=N file.open.label=Open... file.open.key=O file.save.label=Save file.save.key=S file.exit.label=Exit file.exit.key=Q
Here is another example, showing some personalization properties:
name=Ian ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access