|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(4) Here's the basic process for creating a read-only MappedByteBuffer from a file: String filename = ...;FileInputStream input = newFileInputStream(filename);FileChannel channel = input.getChannel();int fileLength = (int)channel.size();MappedByteBuffer buffer =channel.map(FileChannel.MAP_RO, 0, fileLength); You'll find the channel-related classes in the Java.nio.channels package. Once the MappedByteBuffer has been created, you can Access it like any other ByteBuffer. In this particular case though, it is read-only, so any attempt to put something will throw an exception, NonWritableChannelException in this case. If you need to treat the bytes as characters, you must convert the ByteBuffer into a CharBuffer through the use of a character set for the conversion. This character set is specified by the Charset class. You then decode the file contents through the CharsetDecoder class. There is also a CharsetEncoder to go in the other direction. // ISO-8859-1is ISO Latin Alphabet #1Charset charset = Charset.forName("ISO-8859-1");CharsetDecoder decoder = charset.newDecoder();CharBuffer charBuffer = decoder.decode(buffer);These classes are found in the Java.nio.charset package. Regular EXPressionsOnce you've mapped the input file to a CharBuffer, you can do pattern matching on the file contents. Think of running grep or wc on the file to do regular eXPression matching or Word counting, respectively. That's where the Java.util.regex package comes into play and the Pattern and Matcher classes get used.
|