public class Prefs
extends Object
This class was designed to function in a static context prior to the instantiation of whatever class depends on it, which is why it includes the loadPassive() method that stores java.io.IOException for later retrieval instead of throwing it on-the-fly, hence this class will effectively load the preferences as part of your class's definition, which can then be shared in both a static main() class and a non-static constructor, and without having to be reinstantiated later on or passed along as a method variable.
Configuration file format
The format of the configuration file is a simple ASCII text file that can also be edited with any standard ASCII text editor, with each line containing the keyword and value delimited by a space (equal signs can be supported as delimiters by changing the Equal Sign Policy from its default).
Configuration formatting rules are:
Table 1: Special characters Note: Sequences are case-sensitive | |||
UNIX/Linux keystroke | ASCII value | Character's meaning | Sequence |
n/a | 0 | Null | \0 |
CTRL-A | 1 | Start of heading | \A |
CTRL-B | 2 | Start of text | \B |
CTRL-C | 3 | End of text | \C |
CTRL-D | 4 | End of transmit | \D |
CTRL-E | 5 | Enquiry | \E |
CTRL-F | 6 | Acknowledge | \F |
CTRL-G | 7 | Audible bell | \G |
CTRL-H | 8 | Backspace | \H |
CTRL-I | 9 | Horizontal tab | \I or \t |
CTRL-J | 10 | Line feed | \J or #&92;n |
CTRL-K | 11 | Vertical tab | \K |
CTRL-L | 12 | Form feed | \L |
CTRL-M | 13 | Carriage return | \M or \r |
CTRL-N | 14 | Shift out | \N |
CTRL-O | 15 | Shift in | \O |
CTRL-P | 16 | Data link escape | \P |
CTRL-Q | 17 | Device control 1 | \Q |
CTRL-R | 18 | Device control 2 | \R |
CTRL-S | 19 | Device control 3 | \S |
CTRL-T | 20 | Device control 4 | \T |
CTRL-U | 21 | Negative acknowledge | \U |
CTRL-V | 22 | Synchronous idle | \V |
CTRL-W | 23 | End transmission block | \W |
CTRL-X | 24 | Cancel | \X |
CTRL-Y | 25 | End of medium | \Y |
CTRL-Z | 26 | Substitution | \Z |
Escape | 27 | Escape | \[ |
n/a | 28 | File separator | \: |
n/a | 29 | Group separator | \] |
n/a | 30 | Record separator | \/ |
n/a | 31 | Unit separator | \. |
Space bar | 32 | Blank space | \ |
" | 34 | Quotation mark (non-functional) | \" |
Shift-3 | 35 | Octothorpe (" # ") | \# |
\ | 92 | Backslash (" \ ") | \\ |
n/a | hex | Hexadecimal value "hh" | \xhh |
Example
The following example code reads the default ".java.conf" file, and outputs "<Not defined>" if the "NanoTime" value has never been set before. If it has previously been set, then that value will be output. Run this file multiple times and observe the output (previously set value) and the contents of the ".java.conf" file in the current user's home directory (which is updated each time the program is run).
import ca.randolf.util.Prefs;
public class Example {
public static final Prefs PREFS = new Prefs(); // Load user preferences from ".java.conf"
public static void main(String... args) throws java.io.IOException {
System.out.println(PREFS.get("NanoTime", "
A slightly more interesting example is the following code, which also serves to demonstrate the appendMax() method. In this file, the most recent 8 "NanoTime" values are saved, with the oldest (first) one being removed automatically, which can be observed by viewing the ".java.conf" file in the current user's home directory between multiple runs of the example code.
import ca.randolf.util.Prefs;
public class Example {
public static final Prefs PREFS = new Prefs(); // Load user preferences from ".java.conf"
public static void main(String... args) throws java.io.IOException {
System.out.println(PREFS.get("NanoTime", "
Modifier and Type | Field and Description |
---|---|
static String |
DESCRIPTION
Description of this Package (read-only).
|
java.nio.file.Path |
FILENAME
Name of configuration file (defined by a Constructor).
|
static String |
VERSION
Version number of this Package (read-only).
|
Constructor and Description |
---|
Prefs()
Instantiate a Prefs object that defaults to using a configuration file
named ".java.conf" in the logged-in user's home directory.
|
Prefs(java.io.File filename)
Instantiate a Prefs object that uses the specified configuration file in
the logged-in user's home directory.
|
Prefs(java.io.InputStream in)
Instantiate a Prefs object, reading from the specified InputStream's
configuration data in a read-only fashion, then closing the stream using its
standard close() method. Internally, the read-only flag is permanently
set and FILENAME is set to null.
|
Prefs(java.nio.file.Path filename)
Instantiate a Prefs object that uses the specified configuration file in
the logged-in user's home directory.
|
Prefs(String filename)
Instantiate a Prefs object that uses the specified configuration file in
the logged-in user's home directory.
|
Prefs(java.net.URL addr)
Instantiate a Prefs object, reading from the specified URL's openStream()
method's InputStream in a read-only fashion. Internally, the read-only
flag is permanently set and FILENAME is set to null. The URL is also
stored internally so that the load() and loadPassive() methods can be used
subsequently to re-load the configuration data.
|
Modifier and Type | Method and Description |
---|---|
Prefs |
append(String key,
String... values)
Appends the specified String(s) to the underlying (or newly created)
ArrayList<String> for the given key.
|
Prefs |
appendMax(int maximum,
String key,
String... values)
Appends the specified String(s) to the underlying (or newly created)
ArrayList<String> for the given key without exceeding the maximum
number specified. This is useful for maintaining a "most recently used"
list (in the spirit of user-friendly design, I suggest using a higher maximum
number rather than a lower maximum, such as 42 instead of 10).
|
Prefs |
appendMax(String key,
String... values)
Appends the specified String(s) to the underlying (or newly created)
ArrayList<String> for the given key without exceeding the maximum
number specified by the setPolicyAppendMax() method. This is useful for
maintaining a "most recently used" list.
|
String |
get(String key)
Returns the first String from the underlying ArrayList<String> for
the given key.
|
String |
get(String key,
int index)
Returns the specified String from the underlying ArrayList<String>
for the given key.
|
String |
get(String key,
int index,
String defaultValue)
Returns the first String from the underlying ArrayList<String> for
the given key, if it exists. If it doesn't exist, then the supplied
defaultValue will be returned instead.
|
String |
get(String key,
String defaultValue)
Returns the first String from the underlying ArrayList<String> for
the given key, if it exists. If it doesn't exist, then the supplied
defaultValue will be returned instead.
|
ArrayList<String> |
getArrayList(String key)
Returns the underlying ArrayList<String> for the given key.
|
java.io.IOException |
getIOError()
Returns the most recent IOException.
|
String |
getLast(String key)
Returns the last String from the underlying ArrayList<String> for the
given key.
|
LinkedHashMap<String,ArrayList<String>> |
getLinkedHashMap()
Returns the underlying LinkedHashMap<String,ArrayList<String>>
object.
|
boolean |
getPolicyAppendDuplicates()
Indicates the policy on whether all values stored by any method whose name
begins with the word "append" are unique.
|
int |
getPolicyAppendMax()
Indicates the policy for the maximum elements default used by any method
whose name begins with the word "appendMax."
|
boolean |
getPolicyEqualSign()
Indicates the policy about whether one equal sign is a delimiter between
keys and values.
|
boolean |
getPolicyKeepEmptyFile()
Indicates the policy about whether to keep an empty configuration file
(which is 0 bytes) or to delete it (default).
|
String |
glean(String key,
int index,
String defaultValue)
Returns the specified String from the underlying ArrayList<String>
object for the given key, if it exists. If it doesn't exist, then the
supplied defaultValue will be set and returned instead.
|
String |
glean(String key,
String defaultValue)
Returns the first String from the underlying ArrayList<String> object
for the given key, if it exists. If it doesn't exist, then the supplied
defaultValue will be set and returned instead.
|
boolean |
isLoaded()
Indicates whether data was loaded from the configuration file. TRUE
indicates that the data was loaded successfully, and FALSE indicates that it
was not.
|
boolean |
isReadOnly()
Indicates whether the configuration file is read-only. This is set by
the constructor that accepts an InputStream.
|
boolean |
isSaved()
Indicates whether data was saved to the configuration file. TRUE
indicates that the data was saved successfully, and FALSE indicates that it
was not.
|
Prefs |
load()
Attempt to read the contents of the configuration file. If the file
does not exist, or any read error occurs, then the isLoaded() method will
return FALSE from this point forward.
|
Prefs |
loadPassive()
Attempt to read the contents of the configuration file. If the file
does not exist, or any read error occurs, then the isLoaded() method will
return FALSE from this point forward.
|
Prefs |
remove(String key)
Removes the underlying ArrayList<String> for the given key (if it
exists) so that its entry will be deleted from memory, and consequently also
effectively be deleted from the contents of the configuration data upon the
next save operation.
|
Prefs |
save()
Attempt to save the contents of the configuration file. If the file
can not be overwritten or created, or any write error occurs, then the
isSaved() method will return FALSE from this point forward.
|
Prefs |
saveAs(java.io.File filename)
Attempt to save the contents of the configuration data in the alternative
filename that was specified. If the file can not be overwritten or
created, or any write error occurs, then the isSaved() method will return
FALSE from this point forward.
|
Prefs |
saveAs(java.nio.file.Path filename)
Attempt to save the contents of the configuration data in the alternative
filename that was specified. If the file can not be overwritten or
created, or any write error occurs, then the isSaved() method will return
FALSE from this point forward.
|
Prefs |
saveAs(String filename)
Attempt to save the contents of the configuration data in the alternative
filename that was specified. If the file can not be overwritten or
created, or any write error occurs, then the isSaved() method will return
FALSE from this point forward.
|
Prefs |
savePassive()
Attempt to save the contents of the configuration file. If the file
can not be overwritten or created, or any write error occurs, then the
isSaved() method will return FALSE from this point forward.
|
Prefs |
set(String key,
int index,
String value)
Sets or replaces the specified String in the underlying (or newly created)
ArrayList<String> for the given key. If the ArrayList does not
contain enough elements, then the missing number of empty String objects will
be inserted automatically.
|
Prefs |
set(String key,
String... values)
Creates or replaces the underlying ArrayList<String> for the given
key, and populates it with the specified String(s).
|
Prefs |
setArrayList(String key,
ArrayList<String> array)
Sets or replaces the underlying ArrayList<String> for the given key.
|
Prefs |
setPolicyAppendDuplicates(boolean policy)
Specifies the policy on whether all values stored by any method whose name
begins with the word "append" are unique. This is disabled by default,
which means that duplicate values will be eliminated on-the-fly whenever a
method beginning with the word "append" is called.
|
Prefs |
setPolicyAppendMax(int policy)
Specifies the policy for the maximum elements default used by any method
whose name begins with the word "appendMax" (the default is 42).
|
Prefs |
setPolicyEqualSign(boolean policy)
Specifies the policy about whether one equal sign is a delimiter between
keys and values (whitespace characters present in the delimiter set will
still be consumed and discarded as expected).
|
Prefs |
setPolicyKeepEmptyFile(boolean policy)
Indicates the policy about whether to keep an empty configuration file
(which is 0 bytes) or to delete it (default).
|
Prefs |
setReadOnly()
Indicates that the configuration data cannot be saved. Setting this
flag is an irreversible operation (i.e., once this flag has been set to TRUE,
it can never be reverted back to FALSE).
|
public static final String DESCRIPTION
public final java.nio.file.Path FILENAME
public static final String VERSION
public Prefs()
Note: Internally, this constructor calls the loadPassive() method.
public Prefs(java.io.File filename)
Note: Internally, this constructor calls the loadPassive() method.
filename
- Name of configuration file to use (filename may optionally
include relative or absolute path information; if an absolute path is used,
then the user's home directory will be bypassed)public Prefs(java.io.InputStream in)
This constructor is particularly useful when used in conjunction with the java.class.ClassLoader.getSystemResource("example.conf") method is used to load a configuration file from within a JAR file.
Note: Internally, this constructor calls the loadPassive() method.
in
- The InputStream to use to read the configuration datapublic Prefs(java.nio.file.Path filename)
Note: Internally, this constructor calls the loadPassive() method.
filename
- Name of configuration file to use (filename may optionally
include relative or absolute path information; if an absolute path is used,
then the user's home directory will be bypassed)public Prefs(String filename)
Note: Internally, this constructor calls the loadPassive() method.
filename
- Name of configuration file to use (filename may optionally
include relative or absolute path information; if an absolute path is used,
then the user's home directory will be bypassed)public Prefs(java.net.URL addr)
This constructor is particularly useful for reading information from a remote system over a network, such as a web page.
Note: Internally, this constructor calls the loadPassive() method.
addr
- The URL to use to read the configuration datapublic Prefs append(String key, String... values)
key
- The key to usevalues
- The Strings to storegetPolicyAppendDuplicates()
,
setPolicyAppendDuplicates(boolean)
public Prefs appendMax(int maximum, String key, String... values)
Note: The underlying ArrayList<String> will be truncated to comply with the maximum limit (the first elements are removed to make room to add the last elements).
maximum
- The maximum number of String elements that may remain in the
underlying ArrayList<String>. (if 0 is specified, then the maximum set
by the setPolicyAppendMax method will be used instead)key
- The key to usevalues
- The Strings to storegetPolicyAppendDuplicates()
,
setPolicyAppendDuplicates(boolean)
,
getPolicyAppendMax()
,
setPolicyAppendMax(int)
public Prefs appendMax(String key, String... values)
Note: The underlying ArrayList<String> will be truncated to comply with the maximum limit (the first elements are removed to make room to add the last elements).
key
- The key to usevalues
- The Strings to storegetPolicyAppendDuplicates()
,
setPolicyAppendDuplicates(boolean)
,
getPolicyAppendMax()
,
setPolicyAppendMax(int)
public String get(String key)
Note: If the most recent call to the load() method failed, or this key doesn't exist, or the specified String doesn't exist then null will be returned.
key
- The key to usepublic String get(String key, int index)
Note: If the most recent call to the load() method failed, or this key doesn't exist, or the specified String doesn't exist then null will be returned.
key
- The key to useindex
- The position from within the ArrayList of the value to retrieve
(first element is 0; negative values count backwards from the last element)public String get(String key, int index, String defaultValue)
Note: If the most recent call to the load() method failed, or this key doesn't exist, or the specified String doesn't exist then null will be returned.
key
- The key to useindex
- The position from within the ArrayList of the value to retrieve
(first element is 0; negative values count backwards from the last element)defaultValue
- The alternate default value to usepublic String get(String key, String defaultValue)
Note: If the most recent call to the load() method failed, or this key doesn't exist, or the specified String doesn't exist then null will be returned.
key
- The key to usedefaultValue
- The alternate default value to usepublic ArrayList<String> getArrayList(String key)
Note: If the most recent call to the load() method failed, or load() was never called, or this key doesn't exist, then null will be returned.
key
- The key to usepublic java.io.IOException getIOError()
isLoaded()
,
isSaved()
,
load()
,
save()
public String getLast(String key)
Note: If the most recent call to the load() method failed, or this key doesn't exist, or the specified String doesn't exist then null will be returned.
key
- The key to usepublic LinkedHashMap<String,ArrayList<String>> getLinkedHashMap()
Note: If the most recent call to the load() method failed, or load() was never called, then null will be returned.
public boolean getPolicyAppendDuplicates()
append(java.lang.String, java.lang.String...)
,
appendMax(java.lang.String, java.lang.String...)
,
setPolicyAppendDuplicates(boolean)
public int getPolicyAppendMax()
appendMax(java.lang.String, java.lang.String...)
,
setPolicyAppendMax(int)
public boolean getPolicyEqualSign()
setPolicyEqualSign(boolean)
public boolean getPolicyKeepEmptyFile()
setPolicyKeepEmptyFile(boolean)
public String glean(String key, int index, String defaultValue)
Note: If the most recent call to the load() method failed, or this key doesn't exist, or the specified String doesn't exist then defaultValue will be set and returned.
key
- The key to useindex
- The position from within the ArrayList of the value to retrieve
(first element is 0; negative values count backwards from the last element)defaultValue
- The alternate default value to usepublic String glean(String key, String defaultValue)
Note: If the most recent call to the load() method failed, or this key doesn't exist, or the specified String doesn't exist then defaultValue will be set and returned.
key
- The key to usedefaultValue
- The alternate default value to usepublic boolean isLoaded()
getIOError()
,
isSaved()
public boolean isReadOnly()
setReadOnly()
public boolean isSaved()
getIOError()
,
isLoaded()
public Prefs load() throws java.io.IOException
This method may be called multiple times to re-load the configuration data (the existing LinkedHashMap data will be cleared prior to each load attempt).
Note: An attempt to open the file is used internally since hidden files on network drives can sometimes fail the standard tests for existence.
java.io.IOException
- if a read-error occursgetIOError()
,
isLoaded()
public Prefs loadPassive()
This method may be called multiple times to re-load the configuration data (the existing LinkedHashMap data will be cleared prior to each load attempt).
Note: An attempt to open the file is used internally since hidden files on network drives can sometimes fail the standard tests for existence.
Note: The word "Passive" in this method's name indicates that this method does not throw an Exception in the event of an error; the Exception is instead stored for later retrieval by the getIOError() method. This is particularly useful for setting up class-wide configuration settings before any constructors or methods are used, and for access from a static context.
getIOError()
,
isLoaded()
public Prefs remove(String key)
key
- The key to usepublic Prefs save() throws java.io.IOException
This method may be called multiple times to re-save the configuration data, which can be useful for effectively saving incremental changes.
java.io.IOException
- if a write-error occursgetIOError()
,
isSaved()
public Prefs saveAs(java.io.File filename) throws java.io.IOException
This method is particularly useful for saving configuration data that was acquired from an InputStream or a URL, or when the readOnly flag is set.
filename
- Name of configuration file to use (filename may optionally
include relative or absolute path information; if an absolute path is used,
then the user's home directory will be bypassed)java.io.IOException
- if a write-error occurssave()
,
getIOError()
,
isSaved()
,
isReadOnly()
,
setReadOnly()
,
Prefs(java.io.InputStream)
,
Prefs(java.net.URL)
public Prefs saveAs(java.nio.file.Path filename) throws java.io.IOException
This method is particularly useful for saving configuration data that was acquired from an InputStream or a URL, or when the readOnly flag is set.
filename
- Name of configuration file to use (filename may optionally
include relative or absolute path information; if an absolute path is used,
then the user's home directory will be bypassed)java.io.IOException
- if a write-error occurssave()
,
getIOError()
,
isSaved()
,
isReadOnly()
,
setReadOnly()
,
Prefs(java.io.InputStream)
,
Prefs(java.net.URL)
public Prefs saveAs(String filename) throws java.io.IOException
This method is particularly useful for saving configuration data that was acquired from an InputStream or a URL, or when the readOnly flag is set.
filename
- Name of configuration file to use (filename may optionally
include relative or absolute path information; if an absolute path is used,
then the user's home directory will be bypassed)java.io.IOException
- if a write-error occurssave()
,
getIOError()
,
isSaved()
,
isReadOnly()
,
setReadOnly()
,
Prefs(java.io.InputStream)
,
Prefs(java.net.URL)
public Prefs savePassive()
This method may be called multiple times to re-save the configuration data, which can be useful for effectively saving incremental changes.
Note: The word "Passive" in this method's name indicates that this method does not throw an Exception in the event of an error; the Exception is instead stored for later retrieval by the getIOError() method.
getIOError()
,
isSaved()
public Prefs set(String key, int index, String value)
key
- The key to useindex
- The position from within the ArrayList of the value to set
(first element is 0; negative values count backwards from the last element)value
- The String to storepublic Prefs set(String key, String... values)
key
- The key to usevalues
- Any number of String objects for the new ArrayListpublic Prefs setArrayList(String key, ArrayList<String> array)
key
- The key to usearray
- The new ArrayList<String> objectpublic Prefs setPolicyAppendDuplicates(boolean policy)
policy
- TRUE = Allow duplicates; FALSE = Eliminate duplicates (default)append(java.lang.String, java.lang.String...)
,
appendMax(java.lang.String, java.lang.String...)
,
getPolicyAppendDuplicates()
public Prefs setPolicyAppendMax(int policy)
In the spirit of user-friendly design, I suggest using a higher maximum number rather than a lower maximum, such as 42 instead of 10.
policy
- Number of elements (default is 42)appendMax(java.lang.String, java.lang.String...)
,
getPolicyAppendMax()
public Prefs setPolicyEqualSign(boolean policy)
This policy option is useful for reading configuration files that use equal signs as delimiters in their configuration files.
Note: This policy consistently effects all load() and save() methods.
policy
- FALSE = Treat equal signs like other non-whitespace characters
(default); TRUE = Require one equal sign as a special delimiter charactergetPolicyEqualSign()
public Prefs setPolicyKeepEmptyFile(boolean policy)
This policy option is useful for controlling whether empty configuration files are deleted.
Note: This policy consistently effects all save() methods.
getPolicyKeepEmptyFile()
public Prefs setReadOnly()
isReadOnly()