Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 27: NIO, Regular Expressions, and Other Packages 825


// Write the buffer to the output file.
fOChan.write(mBuf); // this copies the file

// Close the channels and files.
fIChan.close();
fIn.close();

fOChan.close();
fOut.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
} catch (ArrayIndexOutOfBoundsException exc) {
System.out.println("Usage: Copy from to");
System.exit(1);
}
}
}

Because the input file is mapped tomBuf, it contains the entire source file. Thus, the call to
write( )copies all ofmBufto the target file. This, of course, means that the target file is an
identical copy of the source file.

Is NIO the Future of I/O Handling?

The NIO APIs offer an exciting new way to think about and handle some types of file
operations. Because of this, it is natural to ask the question, β€œIs NIO the future of I/O handling?”
Certainly, channels and buffers offer a clean way of thinking about I/O. However, they also
add another layer of abstraction. Furthermore, the traditional stream-based approach is
both well-understood and widely used. As explained at the outset, channel-based I/O is
currently designed to supplement, not replace, the standard I/O mechanisms defined in
java.io. In this role, the channel/buffer approach used by the NIO APIs succeeds admirably.
Whether the new approach will someday supplant the traditional approach, only time and
usage patterns will tell.

Regular Expression Processing


Thejava.util.regexpackage supports regular expression processing. As the term is used
here, aregular expressionis a string of characters that describes a character sequence. This
general description, called apattern,can then be used to find matches in other character
sequences. Regular expressions can specify wildcard characters, sets of characters, and
various quantifiers. Thus, you can specify a regular expression that represents a general
form that can match several different specific character sequences.
There are two classes that support regular expression processing:PatternandMatcher.
These classes work together. UsePatternto define a regular expression. Match the pattern
against another sequence usingMatcher.

Pattern

ThePatternclass defines no constructors. Instead, a pattern is created by calling thecompile( )
factory method. One of its forms is shown here:

static Pattern compile(Stringpattern)
Free download pdf