There are actually two ways to find "every charset for which support is available in the current Java virtual machine" (quote source) using a single line of Groovy script. One single-line approach uses a Groovy-specific class while the other single-line approach uses a standard Java class. I'll demonstrate both examples.
The Java Approach
One approach to determining a JVM's supported character sets with a single line of Groovy is to use the Java NIO class provided for that purpose. The following line of Groovy code uses Charset.availableCharsets() to list all character sets supported on the current JVM. The entire Groovy code looks like this:
As is the case with most one-liners, this one is short enough that I can easily try it out without an explicit script file by simply passing this command to the groovy launcher with the
-eoption. This is demonstrated in the next screen snapshot.
The Groovy Approach
Groovy provides a class called CharsetToolkit that can also be used in a single line of Groovy to extract the supported character sets on the current JVM. Here is the code using that class and its getAvailableCharsets() method.
I again show this as used with the
groovylauncher and its
Although both of the above approaches do the job of displaying the JVM's supported character sets, I slightly prefer the Groovier approach because it uses Groovy's property support on the method named
getAvailableCharsetsand does not require an explicit import or scoping. These advantages make it slightly more concise with no loss of readability.
Determining the JVM's Default Charset
Both the Java class
Charsetand the Groovy class
CharsetToolkitalso make it easy in a single line of Groovy script to determine the default character set for the given JVM. This is done via Charset.defaultCharset() or CharsetToolkit.getDefaultSystemCharset(). The "full" script for each is shown in the next two single-line code listings.
The Groovy approach is again shorter, but not by much. The output of running both of these via the
groovylauncher and its
-eoption are shown in the next single screen snapshot.
Acquiring the available character sets supported by a particular JVM as well as determining the default character set supported by a particular JVM are easily accomplished with a single line of Groovy script using either the Java
Charsetclass or the Groovy
CharsetToolkitclass. This is another example of how Groovy is an ideal scripting language for a Java development environment and working with the JVM.