Java Reference
In-Depth Information
20.10. A Taste of New I/O
The java.nio package ("New I/O") and its subpackages give you access to
high performance I/O, albeit with more complexity. Instead of a simple
stream model you have control over buffers, channels, and other ab-
stractions to let you get maximum speed for your I/O needs. This is re-
commended only for those who have a demonstrated need.
The model for rapid I/O is to use buffers to walk through channels of
primitive types. Buffers are containers for data and are associated with
channels that connect to external data sources. There are buffer types for
all primitive types: A FloatBuffer works with float values, for example.
The ByteBuffer is more general; it can handle any primitive type with
methods such as getFloat and putLong . MappedByteBuffer helps you map a
large file into memory for quick access. You can use character set de-
coders and encoders to translate buffers of bytes to and from Unicode.
Channels come from objects that access external data, namely files and
sockets. FileInputStream has a getChannel method that returns a channel
for that stream, as do RandomAccessFile , java.net.Socket , and others.
Here is some code that will let you efficiently access a large text file in a
specified encoding:
public static int count(File file, String charSet, char ch)
throws IOException
{
Charset charset = Charset.forName(charSet);
CharsetDecoder decoder = charset.newDecoder();
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
// Get the file's size and then map it into memory
long size = fc.size();
MappedByteBuffer bb =
fc.map(FileChannel.MapMode.READ_ONLY, 0, size);
CharBuffer cb = decoder.decode(bb);
int count = 0;
 
Search WWH ::




Custom Search