Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Five ways to maximize Java NIO and NIO.2

Build more responsive Java applications with the New Input/Output APIs

  • Print
  • Feedback

Page 5 of 5

5. Character encoding and searching

The final feature of NIO that I want to introduce in this article is charset, a package for converting between different character encodings. Even before NIO, Java built in much of the same functionality through the getBytes method. charset is welcome, though, because it is more flexible than getBytes and easier to implement at a low architectural level, which yields superior performance. This is particularly valuable for searches that must be sensitive to the encoding, collation, and other characteristics of languages other than English.

Listing 4 shows an example of a conversion from Java's native Unicode character encoding to Latin-1.

Listing 4. Character encoding in NIO

String some_string = "This is a string that Java natively stores as Unicode.";
  Charset latin1_charset = Charset.forName("ISO-8859-1");
  CharsetEncode latin1_encoder = charset.newEncoder();
  ByteBuffer latin1_bbuf = latin1_encoder.encode(CharBuffer.wrap(some_string));

Note that Charsets and channels are designed to work well together in order to ensure that programs requiring cooperation between memory mapping, asynchronous I/O, and encoding translation perform adequately.

Conclusion: Of course there's more

The purpose of this article has been to familiarize working Java developers with some of the main (and most useful) facilities of NIO and NIO.2. You can use the foundation established by the examples here to understand some of NIO's secondary methods; for instance, what you've learned about channels will help you make sense of NIO's Path facility for managing symbolic file-system links. See the Resources section as well, for a listing of more in-depth articles about the Java New Input/Output APIs.

About the author

Cameron Laird began writing Java code before it was called Java and has contributed occasionally to JavaWorld in the years since then. Keep up with his coding and writing through Twitter as @Phaseit.

Read more about Core Java in JavaWorld's Core Java section.

  • Print
  • Feedback

Resources