Java Reference
In-Depth Information
Two other entities used by NIO are charsets and selectors. A charset defines the way
that bytes are mapped to characters. You can encode a sequence of characters into bytes
using an encoder . You can decode a sequence of bytes into characters using a decoder . A
selector supports key-based, non-blocking, multiplexed I/O. In other words, selectors en-
able you to perform I/O through multiple channels. Selectors are most applicable to
socket-backed channels.
Beginning with JDK 7, NIO was substantially enhanced, so much so that the term
NIO.2 is often used. The improvements included three new packages ( java.nio.file ,
java.nio.file.attribute , and java.nio.file.spi ); several new classes, interfaces, and meth-
ods; and direct support for stream-based I/O. The additions greatly expanded the ways in
which NIO can be used, especially with files.
It is important to understand that NIO does not replace the I/O classes found in java.io ,
which are discussed in this chapter. Instead, the NIO classes are designed to supplement
the standard I/O system, offering an alternative approach, which can be beneficial in some
circumstances.
Using Java's Type Wrappers to Convert Numeric Strings
Before leaving the topic of I/O, we will examine a technique useful when reading numeric
strings. As you know, Java's println( ) method provides a convenient way to output various
types of data to the console, including numeric values of the built-in types, such as int and
double . Thus, println( ) automatically converts numeric values into their human-readable
form. However, methods like read( ) do not provide a parallel functionality that reads and
converts a string containing a numeric value into its internal, binary format. For example,
there is no version of read( ) that reads a string such as "100" and then automatically con-
verts it into its corresponding binary value that is able to be stored in an int variable. In-
stead, Java provides various other ways to accomplish this task. Perhaps the easiest is to
use one of Java's type wrappers .
Java's type wrappers are classes that encapsulate, or wrap , the primitive types. Type
wrappers are needed because the primitive types are not objects. This limits their use to
some extent. For example, a primitive type cannot be passed by reference. To address this
kind of need, Java provides classes that correspond to each of the primitive types.
The type wrappers are Double , Float , Long , Integer , Short , Byte , Character , and
Boolean . These classes offer a wide array of methods that allow you to fully integrate
the primitive types into Java's object hierarchy. As a side benefit, the numeric wrappers
also define methods that convert a numeric string into its corresponding binary equivalent.
Search WWH ::




Custom Search