image
 
image
Java Source Code



CharIterator     CommandLine     ConsoleInfo     ConsoleStream     Const     CssFile     DelimitedFile     FileLockingProtocol     GlobalProperties     GUID     HtmlFile     MultiOutputStream     NativeMethods     NativeMethods.c     NCString     PolynomialFit     PrimeNumber     StreamGobbler     TextFile     TextReader     TextReaderIterator     TextWriter     TreeMapOfHashMaps     UDateTime     UMath     UString     UStringPairs     Util     XFile     XProperties     XRandom     XString     XStringsIterator     ZipFile

Instances of this class are Iterators over the characters in a text file. The text file is treated as an ordered list of chars. This provides an alternative and cleaner paradigm (an iterator pattern) for reading a text file one character at a time from the one provided by the BufferedReader or TextReader class.

Instances of this class are for parsing and making sense of the command line arguments (tokens) passed into a program, similar to the GNU getopt() command line parser. Tokens may be placed in any order on the command line.
Caveat: A token representing a control that allows an optional argument should not immediately precede a token representing a non-control unless the token representing the non-control is intended to be the argument for the token representing the control.
Instances of this class support command line options that begin with a single dash. Unlike GNU getopt(), instances of this class handle long (multi-character) controls just like single character ones, without requiring any special syntax. They therefore do not need or support command line options that begin with a double dash. They do not support multiple option characters being packed together into a single string preceded by a single dash (multiple options specified together ) as such a construct would be indistinguishable from a long (multi-character) control preceded by a single dash (which instances of this class do support).

Background from Wikipedia

A long standing issue with command line programs was how to specify options; early programs used many ways of doing so, including:
=> single character options (-a),
=> multiple options specified together (-abc is equivalent to -a -b -c),
=> multi-character options (-inum),
=> options with arguments (-a arg, -inum 3, -a=arg),
=> and different prefix characters (-a, +b, /c).
The getopt() function was written to be a standard mechanism that all programs could use to parse command-line options so that there would be a common interface that everyone could depend on. As such, the original authors picked out of the variations support for single character options, multiple options specified together, and options with arguments (-a arg or -aarg), all controllable by an option string.

getopt() dates back to at least 1980 and was first published by AT&T at the 1985 UNIFORUM conference in Dallas, Texas. Versions of it were subsequently picked up by other flavors of Unix (BSD 4.3, GNU/Linux, etc.). It is specified in the POSIX.2 standard. Derivatives of getopt() have been created for many programming languages to parse command-line options.

A GNU extension, getopt()_long, allows parsing of more readable, multi-character options, which are introduced by two dashes instead of one. The choice of two dashes allows multi-character options (--inum) to be differentiated from single character options specified together (-abc). The GNU extension also allows an alternative format for options with arguments: --name=arg.

Of the ways to specify options mentioned above, instances of this class support the following:
=> single character options (-a),
=> multi-character options preceded by a single dash (-inum),
=> options with arguments and no equals sign (-a arg, -inum 3);
and do not support the following:
=> multiple options specified together (-abc is equivalent to -a -b -c),
=> multi-character options preceded by a double dash (--inum)
=> options with arguments and an equals sign (-a=arg),
=> different prefix characters (+b, /c).
=> alternative format for options with arguments: --name=arg.
Additionally, instances of this class support the following:
=> arguments separated from their option character by whitespace (-a arg),
=> arguments not separated from their option character by whitespace (-aarg),
=> arguments inside of quotes (-a "arg", -a"arg").
Instances of this class support the following types of command line tokens:
=> optional options that may or may not be included on the command line,
=> mandatory options that must be included on the command line,
=> options that cannot include an argument,
=> options that may or may not include an optional argument,
=> options that must include a mandatory argument,
=> file pathname specifiers (with or without wildcard characters).
-> All tokens on the command line without a beginning dash are interpreted as being either the argument for an immediately preceding option or as a file pathname specifier. If the token immediately preceding is an option requiring an argument or is an option that accepts an optional argument, then the token without a beginning dash is interpreted as the argument to the option. If the token immediately preceding is not an option or is an option that does not accept an argument, then the token without a beginning dash is interpreted as a file pathname specifier.

Obviously, if a preceding token is one that requires or accepts an argument and it already has an argument associated with it, then the following token without a beginning dash is not considered the preceding option's argument or any part of it. It is considered a file pathname specifier.

Tokens are separated from each other on the command line by any number of consecutive whitespace characters (not including an end of line, of course). To group a series of whitespace separated words or strings together into one option argument or file pathname specifier, the group must be enclosed in double quotes. For example, to group these words: Life's short, code hard! together as the argument for the -advice option, group them and place the group next to the option as follows: -advice  "Life's short, code hard!" or -advice"Life's short, code hard!".

Instances of this class represent a Windows console window. This class leverages the Java Native Access (JNA) libraries which are located at: https://github.com/twall/jna.

Salient characteristics of ConsoleInfos are:

=> It accesses a native Windows library to get the Windows-specific console screen properties.

Instances of this class write messages to the console in a predefined format that is suitable for logging. An instance writes single-line messages in this format:
                                          2007-01-23 11:12:29:414 --->  This is a single-line console message.
                                       
It writes multi-line messages in this format:
                                          2007-01-23 11:50:53:414 --->  =====================================================
                                                                        =====================================================
                                                                        This is a wordy, multi-line console message that is
                                                                        intended to demonstrate word wrapping and multi-line
                                                                        message boxing.
                                                                        -----------------------------------------------------
                                       
It writes multi-line messages that have a title in this format:
                                          2007-01-23 11:50:53:414 --->  =====================================================
                                                                        ======================| Title |======================
                                                                                              ---------
                                                                        This is a wordy, multi-line console message that is
                                                                        intended to demonstrate word wrapping and multi-line
                                                                        message boxing.
                                                                        -----------------------------------------------------
                                       
It writes multi-line messages that have a multi-line title in this format:
                                          2007-01-23 11:50:53:414 --->  =====================================================
                                                                        =====|  This is a wordy, multi-line title that  |====
                                                                        =====| demonstrates how titles are word-wrapped |====
                                                                        =====|      and centered in the title box.      |====
                                                                             --------------------------------------------
                                                                        This is a wordy, multi-line console message that is
                                                                        intended to demonstrate word wrapping and multi-line
                                                                        message boxing.
                                                                        -----------------------------------------------------
                                       

Instances of this class are made up of static constants that are potentially common to more than one of the other classes in this package. They are used instead of literals in the other classes to eliminate the problems of misspellings and wrong character case. Use of these constants instead of the actual literals also makes maintenance easier. If a literal needs to be changed, it only has to be changed in this file, not in every file where the constant is used.

Instances of this class represent an CSS file. Salient characteristics of a CssFile are:
=> it contains text in CSS format and is intended for consumption by a web browser,
=> it can be optimized (compressed) and still be interpreted correctly by a browser,
-> this class defines a public instance method - optimize() - that will remove all the comments and delete all the Unnecessary whitespace from the file.
This class is derived from the TextFile class. The abstraction it layers on top of TextFile includes the following:
=> it contains only CSS-encoded text.

Objects of this class read delimited files such as tab-separated-values files (.tsv files) and comma-separated-values files (.csv files such as those used by MS Excel). The file is first cleansed of garbage characters and then parsed into the tokens that are separated by the delimiter. The default delimiter is the comma and the default quote character is the double quote. These special characters may be changed by calling the appropriate setter methods.

Salient characteristics of a DelimitedFile include:

=> The first line of the file is expected to contain column headers. Instances of this class use the delimited Strings on that first line to determine how many columns are in the file as well as to identify each column.
=> The comma character is considered the delimiter by default.
=> The delimiter can be changed from the comma to anything else through a method call,
=> The double quote character is considered the quote character by default.
=> The quote character can be changed from the double quote to anything else through a method call,
=> Instances of this class can return lines of the file in already parsed token arrays.
Subclass

This class is derived from the TextFile class. The abstraction it layers on top of TextFile includes the following:

=> It interprets each line of text in the file as a series of delimited Strings.
=> The first line of the file is expected to contain column headers.
=> All lines subsequent to the first line (column headers line) are expected to contain a series of Strings Separated by the delimiter, which is a comma by default.
=> All lines subsequent to the first are expected to have as many delimiter-separated Strings as there are in the First line.

Objects of this class implement a cooperative file-locking protocol. A cooperative file-locking protocol is used to control access to a shared resource. In a cooperative file-locking protocol, the participating programs use a lock file as a token that gives permission to the holder of the token to access the shared resource. The holder of the token is the program that creates the lock file. When the holder of the token is done, it deletes the lock file.

When a program wants to access the shared resource, it checks to see if the lock file exists. If it does, the program must wait to access the shared resource. If the lock file does not exist, the program creates it and accesses the shared resource. While the lock file exists, other programs are prevented from accessing the shared resource. When the program is done accessing the shared resource, it deletes the lock file and in so doing, allows another program to access the shared resource.

Note: Using the Standard Java SDK method createNewFile() from within getLock() is the key to making this whole FileLockingProtocol class work because it is an atomic operation. In other words, two processes cannot both call createNewFile() at the same time and both succeed. createNewFile() atomically creates a new, empty file if and only if the file does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other file-system activities that might affect the file.


Instances of this class represent properties that are available to a program, primarily from the operating system environment. These objects give access to the system's environment variables and provide services related to using the environment variables. The object may also be used like any other properties object to store any additional key-value pairs that the user chooses. Likely candidates for these additional key-value pairs include command line options.

Java makes it difficult to get environment variables. In the past you could use System.getenv("environmentVariableName") to retrieve environment variables. However, that now deprecated method will throw the following exception if you attempt to call it:

Exception in thread "main" java.lang.Error: getenv no longer supported, use properties and -D instead ...
Sun decided to deprecate the method because environment variables are a platform-specific feature, and some platforms, MacOS for example, don't have the concept of an environment variable.

This class solves the problem in a fairly portable way and without resorting to using the Java Native Interface, which is an approach that most definitely violates portability.


Objects of this class create a pure identifier that is guaranteed to be unique in the world under the following conditions:
  • the machine on which it is generated takes more than one second to reboot,
  • the machine's clock is never set backward, and
  • the machine does not have the same Internet address as any other machine in the world that generates a GUID at the exact same internal clock time as this machine.
A GUID is generated by pairing a UID with the host machine's InetAddress.

Instances of this class represent an HTML file. Salient characteristics of an HtmlFile are:
=> it contains text in HTML format and is intended for consumption by a web browser,
=> it can be optimized (compressed) and still be interpreted correctly by a browser,
-> this class defines a public instance method - optimize() - that will remove all the comments and delete all the unnecessary whitespace from the file.
This class is derived from the TextFile class. The abstraction it layers on top of TextFile includes the following:
=> it contains only HTML-encoded text.

Instances of this class represent a group of OutputStreams, all of which are sent the exact same output. It allows you to send the same output to multiple endpoints with one I/O operation. A simple example is if you wanted to send the same output from a program to two separate files. You would open both files, each as a separate and independent OutputStream and then "wrap" both those OutputStreams inside of one MultiOutputStream. Each write method call on the MultiOutputStream would be routed by the MultiOutputStream to both of the wrapped file OutputStreams.

Another more interesting example allows you to make Java's standard console output - System.out (or System.err) send its output to both the normal System.out (or System.err) and also to a file for logging purposes. To do so, you would open the log file as a independent OutputStream and then wrap it together with System.out (or System.err) inside a single MultiOutputStream. Then you would wrap the MultiOutputStream in a PrintStream and set the PrintStream as System.out (or System.err).

Salient characteristics of a MultiOutputStream are:

  • It allows the same output to be sent to multiple OutputStreams with a single output request.
  • It allows additional OutputStreams to be added to the MultiOutputStream at any time with no practical limit on their numbers.
  • It allows OutputStreams to be removed from the MultiOutputStream at any time.
This class is derived from the OutputStream class. The abstraction it layers on top of OutputStream includes the following:
  • It allows the same output to be sent to multiple OutputStreams with a single output request.

This is the Java portion of the set of files that are required to allow calls directly into the operating system (Windows) from a Java class.

Java uses JNI (Java Native Interface) to access functionality that resides outside of the Java environment on the host computer. On Windows, JNI requires a Windows DLL which is written in C and compiled. This DLL contains functions that call directly into Windows. For example, to set the created date on a Windows file (an operation that is not supported in Java), the DLL would have a function with a JNI-defined signature and name, say "Java_NativeMethodsPath_setCreated" that calls a "set" function in Windows. There would also be a Java file that contains methods that correspond one-for-one with the methods in the DLL. A Java SDK-provided JNI tool links each of the Java methods to its corresponding DLL function as part of the Java compilation process.

This is the Java file that contains methods that correspond one-for-one with the methods in the DLL.


This is the C portion of the set of files that are required to allow calls directly into the operating system (Windows) from a Java class.

Java uses JNI (Java Native Interface) to access functionality that resides outside of the Java environment on the host computer. On Windows, JNI requires a Windows DLL which is written in C and compiled. This DLL contains functions that call directly into Windows. For example, to set the created date on a Windows file (an operation that is not supported in Java), the DLL would have a function with a JNI-defined signature and name, say "Java_NativeMethodsPath_setCreated" that calls a "set" function in Windows. There would also be a Java file that contains methods that correspond one-for-one with the methods in the DLL. A Java SDK-provided JNI tool links each of the Java methods to its corresponding DLL function as part of the Java compilation process.

This is the C file that compiles into a DLL file containing functions that call directly into Windows.


This class is intended to act as a full, and more powerful replacement for Java's String class for representing Strings without case-distinctions. In other words, all the methods of this class ignore case.

The Java String class (String) is final, meaning that you cannot add methods to it or improve it in any way by creating a subclass of it. This is an annoyance because it forces the user to create a separate String utility class containing any additional methods the user needs for Strings, and to then switch back and forth between the String class and the String utility class.

This class provides methods that are equivalent to all the String class's instance and static methods. In other words, it replicates the String class's entire API. As an improvement over the String class, the methods of this class accept generic types in place of Java's String parameter. This means that objects of any class that can be converted into a String can be passed into any of the NCString methods where the corresponding String method requires Strings.

NCString goes further by providing additional methods not found in the String class. These additional methods greatly extend the power of NCString beyond that of String.

Taken together, the above mentioned characteristics of NCString result in a class that can be used as a more powerful replacement for the String class. The one thing that is lost when using NCString instead of String is Java's support for direct assignment of String literals to String variables. NCString does not have this support and all NCStrings must be created with an NCString constructor. For example, the following code:

                                          String exampleString = "This is a test";
                                          someClass.someMethodThatTakesAStringParameter(exampleString);
                                       
would have to change as follows when using NCString as a substitute for String:
                                          NCString exampleString = new NCString("This is a test");
                                          someClass.someMethodThatTakesAStringParameter(exampleString.toString());
                                       
The most obvious differences between this class and the standard Java String class are:
  • Strings of this class are case-insensitive. (The name NCString means "No-Case String".)
  • This class is a subclass of XString.
  • Unlike the String class, this NCString class is not final. Therefore, it is possible to add methods to it at any time.
  • Most of the methods of this class take generic parameters where the corresponding methods of the standard Java String class would take concrete parameter types.
  • While providing exactly the same methods as the String class, this class also offers numerous additional methods that make NCStrings much more powerful than Strings.

This class determines the polynomial that is a best fit to a set of data points. When the user instantiates an object of this class, the user specifies the set of data points to fit a polynomial to and also specifies the order of the polynomial.

This current version implements the least-squares algorithm to determine the polynomial.


This class provides static methods for finding prime numbers. The methods included allow the user to:
  • Generate a text file containing all the prime numbers between 0 and a specified maximum number,
  • Generate a text file containing all the prime numbers between a specified minimum number and a specified maximum number,
  • Generate a text file containing all the prime numbers that fall within the range of plus and minus 100 of a specified number, inclusive,
  • Determine whether or not a specified number is a prime number,
  • Return the maximum prime number that is within Java's integer range,
  • Return first prime number that is greater than or equal to a specified number,
  • Generate a array containing all the prime numbers that fall within the range of plus and minus 100 of a specified number, inclusive.

Instances of this class run as independent threads, intercept an InputStream, and redirect it to cOut and optionally to another OutputStream.

I took the idea for this class, information about how to use it, and the term "StreamGobbler" from an article called " When Runtime.exec() won't ".

StreamGobblers are particularly useful for intercepting and emptying stdout and stderr when an external program is executed from inside a Java program. (From the external program's perspective, stdout and stderr are OutputStreams. But from the perspective of the Java program that is running the external program, the external program's stdout and stderr are InputStreams.)

The reason StreamGobbler is useful in this scenario is because some native platforms only provide a limited buffer size for the standard input and output streams, and failure to promptly write the input stream or read the output stream of the external program may cause the external program to block, and even deadlock. I can personally testify that this happens and that without the information found in the article cited above, these bugs are very hard to figure out.


Objects of this class represent Files containing lines of text. A lot of things can be done with a file once you know that it is a text file and this class provides methods to do many of those things. Most of the methods provided here operate on the individual lines of a text file, permitting such things as de/entabbing, string replacement, trimming in various ways, sorting, tabularizing, etc.. And since TextFile is a subclass of XFile, all the things that can be done with an XFile can also be done with a TextFile.

Instances of this class are convenience objects for buffered reading of character files. A TextReader reads text from a character-input stream, buffering characters so as to provide efficient reading.

Creating a TextReader is equivalent to wrapping a FileReader in a BufferedReader with the exception that the TextReader readLine() method returns an XString instead of a String. These two statements are [almost] equivalent:

                                          BufferedReader in = new BufferedReader(new FileReader("foo.in"));
                                          TextReader     in = new TextReader("foo.in");
                                       

Instances of this class are Iterators over the lines in a text file. The text file is treated as an ordered list of XStrings. Each XString contains one line of the text file. This provides an alternative and cleaner paradigm (an iterator pattern) for reading a text file from the one provided by the BufferedReader or TextReader class.

An advantage of using a TextReaderIterator instead of a BufferedReader or TextReader is that you don't have to explicitly cast the objects returned by next() and peek() to XString.


Instances of this class are convenience objects for buffered writing of character files. A TextWriter writes text to a character-output stream, buffering characters so as to provide efficient writing.

Creating a TextWriter is equivalent to wrapping a FileWriter in a BufferedWriter. These two statements are equivalent:

                                          BufferedWriter out = new BufferedWriter(new FileWriter("foo.out"));
                                          TextWriter     out = new TextWriter("foo.out");
                                       

Instances of this class read a file in this format:
                                          [string1]
                                          key1=value1
                                          key2=value2
                                          [string2]
                                          key1=value1
                                          key2=value2
                                          key3=value3
                                       
And create a TreeMap in which each node is keyed with an XString that is enclosed within [ ]'s in the file. The value for the key is the data that is between the line of the file with the key and the next line of the file containing another key.

Each node in the TreeMap is a HashMap made up of the key/value pairs that appear following the TreeMap key.

Blank lines and comments in the file are ignored. Comments are any line that starts with the XString "//".

For example, if a file named "sequence.txt" contained these lines:

                                          [0000.00.00]
                                          other   = None

                                          [1955.10.25]
                                          city    = Roswell, NM
                                          address = First Street

                                          [1959.07.01]
                                          city    = Roswell, NM
                                          address = 19 Wildy Dr.

                                          [1965.07.01]
                                          city    = North Las Vegas, NV
                                          address = East Piper

                                          // this is a comment and it is ignored
                                       
Then this class would create a TreeMap containing the following keys:
                                          "0000.00.00"
                                          "1955.10.25"
                                          "1959.07.01"
                                          "1965.07.01"
                                       
And the value for the node with the key of "1959.07.01" would be a HashMap containing the following key/value pairs:
                                          key          value
                                          ---------    --------------
                                          "city"       "Roswell, NM"
                                          "address"    "19 Wildy Dr."
                                       

This is a utility class that contains static methods that supplement the Date class. It is an application of the "Utility Pattern".

The Utility pattern is used for classes that do not require instantiation and only have static methods. As the utility class is stateless, all parameters in each method must pass all necessary information to the method.


This class is intended to act as a full, and more powerful replacement for the methods of Java's Math class or as a source of Math-related static utility methods.

The Java Math class (Math) is final, meaning that you cannot add methods to it or improve it in any way by creating a subclass of it. This is an annoyance because it forces the user to create a separate Math utility class containing any utility methods the user needs for Math, and to then switch back and forth between the Math class and the Math utility class.

This class provides static methods that are equivalent to all the Math class's methods. In other words, it replicates the Math class's entire API. UMath goes further by providing additional methods not found in the Math class. These additional methods greatly extend the power of UMath beyond that of Math.

Taken together, the above mentioned characteristics of UMath result in a class that can be used as a more powerful replacement for Math's API.

The most obvious differences between this class and the standard Java Math class are:

  • While providing exactly the same methods as the Math class, this class also offers numerous additional methods that extend the Math class functionality.

This class is intended to act as a full, and more powerful replacement for the methods of Java's String class or as a source of String-related static utility methods.

The Java String class (String) is final, meaning that you cannot add methods to it or improve it in any way by creating a subclass of it. This is an annoyance because it forces the user to create a separate String utility class containing any utility methods the user needs for Strings, and to then switch back and forth between the String class and the String utility class.

This class provides static methods that are equivalent to all the String class's instance and static methods. In other words, it replicates the String class's entire API with the caveat that all of String's instance methods are provided as static methods by UString. And since all the methods are static, they all require a String parameter to operate upon. However, as an improvement over the String class, this String parameter is generic in all the UString methods. This means that objects of any class that can be converted into a String can be passed into any of the UString methods. (UString also makes public the method it uses for converting instances of other classes to Strings.)

UString goes further by providing additional methods not found in the String class. These additional methods greatly extend the power of UString beyond that of String.

Taken together, the above mentioned characteristics of UString result in a class that can be used as a more powerful replacement for String's API. Since UString is a utility* class, instances of UString cannot be created. String variables must be created as instances of Java's String class and then UString can be used to perform all the operations on them. This limitation of UString is eliminated by another custom class named "XString".

The most obvious differences between this class and the standard Java String class are:

  • Because they are all static, the methods of this class require a String parameter to operate upon.
  • Unlike the String class, this UString class is not final. Therefore, it is possible to add methods to it at any time.
  • Most of the methods of this class take generic parameters where the corresponding methods of the standard Java String class would take concrete parameter types.
  • While providing exactly the same methods as the String class, this class also offers numerous additional methods that extend the functionality that can be applied to Strings.
  • This class provides case-insensitive versions of many of the String class methods. These are named by appending "IgnoreCase" to the end of the method name.

This is a utilities class containing static methods for reading pairs of strings from a text file. Each line of the file must contain 1 pair of strings, separated from each other by a comma. The file may contain blank lines (lines that are empty or that contain only SPACE characters). These blank lines are ignored.
Note: A line containing any other whitespace character such as a tab, backspace, formfeed, etc., IS NOT A BLANK LINE. A blank line must be entirely empty or contain ONLY SPACES.
The comma, known as the default "string separator", may be changed to any other single character EXCEPT A SPACE.
The string separator can ONLY be changed by placing a single non-space character on the FIRST non-blank line of the file. If the first non-blank line of the file is found to contain just one non-space character, that character is used as the string separator instead of the default, which is a comma.
The file may contain comments. Comments are demarcated by a comment delimiter character. There is no default comment delimiter and consequently, by default, comments are not allowed in the file.
The comment delimiter can ONLY be set by placing a single non-space character on the FIRST non-blank line of the file AFTER a string separator line. If the first non-blank line after a string separator line of the file is found to contain just one non-space character, that character is used as the comment delimiter.
Notice: A comment delimiter may only be defined if a string separator has already been defined in the file.
When a comment delimiter is included in the file, comments may be placed anywhere else in the file. The span of a comment is from each comment delimiter [inclusive] to the end of the line on which the comment delimiter is found. Comments are ignored.
Warning: If spaces are placed between the end of the second string on a line and the start of a comment, those spaces will be considered part of the second string [unless trim and/or squeeze are set to true - see below].
Metacharacters (escape sequences) may be include in the strings in the file. These are translated into the actual character when the string is read. These metacharacters are translated as follows:
                                          +---------------+----------------------+
                                          | Metacharacter | Is Translated Into a |
                                          +---------------+----------------------+
                                          |      \n       |      newline         |
                                          |      \t       |      tab             |
                                          |      \b       |      backspace       |
                                          |      \f       |      formfeed        |
                                          |      \r       |      carriage return |
                                          +---------------+----------------------+
                                       
By setting the "trim" and/or "squeeze" parameters of the method that reads the file, space characters may be included in the file for formatting purposes to improve readability and yet not be considered part of either of the strings on any line.
=> the "trim" setting will strip away all leading and trailing spaces from each string in the file.
=> the "squeeze" setting will strip away all leading and trailing and interspersed spaces from each string in the file.

This class is an implementation of the Utility pattern. Calling it a pattern is a way of legitimizing what is just a collection of a whole bunch of stuff that doesn't really belong together. Here's how the Utility pattern is characterized:
The Utility pattern is a software pattern that is used for utility classes that do not require instantiation and only have static methods. It is a stateless class and so no instance can be created. Good candidates for utility classes are convenience methods that can be grouped together functionally.
All the methods in this class are static and instantiating a Utility class object would be pointless. The methods are simply used in accordance with the procedural programming paradigm and there is nothing object oriented about them.

This class is essentially a collection of miscellaneous methods. They are gathered together in this Utility class because they are generally unrelated to each other or are related to only a very small number of others. They are all static and therefor they don't require persistent state data which is a prime driver of the need for a "real" class. Furthermore, no substantial subset of them is cohesive enough to justify cluttering the class library namespace by grouping them together into a real class. With that said, there is a lot of very useful functionality in this class.


This class provides methods to supplement the capabilities provided by a class that is part of the JDK, J2EE, or some other 3rd party library. The extensions are provided by way of this subclass of the 3rd party class.

In particular, this class extends the capabilities of the File class. Like the File class, this class provides methods that manipulate and get parts of a file's name or path and retrieves other information about a file that the File class does not. Unlike the File class, this class also provides methods for modifying the content of the file; among others, this includes methods that encrypt, decrypt, copy, and append the file. The class provides a number of other miscellaneous file management methods as well.


This class extends the capabilities of the Properties class.

Objects of this class are persistent sets of properties that are loaded from a file.

Each XProperties object is loaded by reading a property list (key and element pairs) from a file. The file is assumed to be using the ISO 8859-1 character encoding. Every property occupies one line of the file. Each line is terminated by a line terminator (\n or \r or \r\n). Lines from the file are processed until the end of file is reached on the file.

A line that contains only whitespace or whose first non-whitespace character is an ASCII # is ignored (thus, # indicate comment lines).

Every line other than a blank line or a comment line describes one property to be added to the table (except that if a line ends with \, then the following line, if it exists, is treated as a continuation line, as described below). The key consists of all the characters in the line starting with the first non-whitespace character and up to, but not including, the first ASCII =, :, or whitespace character. All of the key termination characters may be included in the key by preceding them with a \. Any whitespace after the key is skipped; if the first non-whitespace character after the key is = or :, then it is ignored and any whitespace characters after it are also skipped. All remaining characters on the line become part of the associated element XString. Within the element XString, the ASCII escape sequences \t, \n, \r, \\, \", \', \ (a backslash and a space), and \\uxxxx are recognized and converted to single characters. Moreover, if the last character on the line is \, then the next line is treated as a continuation of the current line; the \ and line terminator are simply discarded, and any leading whitespace characters on the continuation line are also discarded and are not part of the element XString.

As an example, each of the following four lines specifies the key "Truth" and the associated element value "Beauty":

                                          Truth = Beauty
                                             Truth:Beauty
                                          Truth       :Beauty
                                       
In another example, the following three lines specify a single property:
                                          fruits            apple, banana, pear, \
                                                                            cantaloupe, watermelon, \
                                                                            kiwi, mango
                                       
The key is "fruits" and the associated element is:
                                          "apple, banana, pear, cantaloupe, watermelon,kiwi, mango"
                                       
Note that a space appears before each \ and consequently a space appears after the commas following "pear" and "watermelon" in the final result. The \ itself, the [invisible] line terminator, and the leading whitespace on the continuation line are all discarded. Finally, a third example, the lines:
                                          cheese
                                          crackers =
                                       
specify that the keys are "cheese" and "crackers" and the associated element is the empty String for both "cheese" and "crackers".

This class provides methods to supplement the capabilities provided by a class that is part of the JDK, J2EE, or some other 3rd party library. The extensions are provided by way of this subclass of the 3rd party class.

In particular, this class extends the capabilities of the Random class by adding a couple of methods that generate random XStrings of parameter-specified lengths.

The following is the class description of the Random class, which this XRandom class inherits:

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.) If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods. The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method Math.random() simpler to use.

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.


This class is intended to act as a full, and more powerful replacement for Java's String class.

The Java String class (String) is final, meaning that you cannot add methods to it or improve it in any way by creating a subclass of it. This is an annoyance because it forces the user to create a separate String utility class containing any additional methods the user needs for Strings, and to then switch back and forth between the String class and the String utility class.

This class provides methods that are equivalent to all the String class's instance and static methods. In other words, it replicates the String class's entire API. As an improvement over the String class, the methods of this class accept generic types in place of Java's String parameter. This means that objects of any class that can be converted into a String can be passed into any of the XString methods where the corresponding String method requires Strings.

XString goes further by providing additional methods not found in the String class. These additional methods greatly extend the power of XString beyond that of String.

Taken together, the above mentioned characteristics of XString result in a class that can be used as a more powerful replacement for the String class. The one thing that is lost when using XString instead of String is Java's support for direct assignment of String literals to String variables. XString does not have this support and all XStrings must be created with an XString constructor. For example, the following code:

                                          String exampleString = "This is a test";
                                          someClass.someMethodThatTakesAStringParameter(exampleString);
                                       
would have to change as follows when using XString as a substitute for String:
                                          XString exampleString = new XString("This is a test");
                                          someClass.someMethodThatTakesAStringParameter(exampleString.toString());
                                       
The most obvious differences between this class and the standard Java String class are:
  • Unlike the String class, this XString class is not final. Therefore, it is possible to add methods to it at any time.
  • Most of the methods of this class take generic parameters where the corresponding methods of the standard Java String class would take concrete parameter types.
  • While providing exactly the same methods as the String class, this class also offers numerous additional methods that make XStrings much more powerful than Strings.
  • This class provides case-insensitive versions of many of the String class methods. These are named by appending "IgnoreCase" to the end of the method name.

Instances of this class are iterators over collections or Files of XStrings.

If an XStringsIterator instance is set to be non-case-sensitive, its methods will return instances of a case-insensitive subclass of XString, namely an NCString.

The advantage of using a XStringsIterator instead of a TextReaderIterator or Iterator is that you don't have to explicitly cast the objects returned by next() and peek() to XString.


Objects of this class represent archive files that are implemented with the ZIP file standard. ZipFiles can be created, have files added to them, deleted from them, etc. And since ZipFile is a subclass of XFile, all the things that can be done with an XFile can also be done with a ZipFile.