Java Reference
In-Depth Information
}
Pattern p = Pattern . compile ( args [ 0 ]);
for
for ( int
int i = 1 ; i < args . length ; i ++)
process ( p , args [ i ]);
}
static
static void
void process ( Pattern pattern , String fileName ) throws
throws IOException {
// Get a FileChannel from the given file.
FileChannel fc = new
new FileInputStream ( fileName ). getChannel ();
// Map the file's content
ByteBuffer buf = fc . map ( FileChannel . MapMode . READ_ONLY , 0 , fc . size ());
// Decode ByteBuffer into CharBuffer
CharBuffer cbuf =
Charset . forName ( "ISO-8859-1" ). newDecoder (). decode ( buf );
Matcher m = pattern . matcher ( cbuf );
while
while ( m . find ()) {
System . out . println ( m . group ( 0 ));
}
}
}
The NIO version shown in Example 4-5 relies on the fact that an NIO Buffer can be used as
a CharSequence . This program is more general in that the pattern argument is taken from the
command-line argument. It prints the same output as the previous example if invoked with
the pattern argument from the previous program on the command line:
java regex.GrepNIO "[A-Za-z][a-z]+" ReaderIter.java
You might think of using \w+ as the pattern; the only difference is that my pattern looks for
well-formed capitalized words, whereas \w+ would include Java-centric oddities like
theVariableName , which have capitals in nonstandard positions.
Also note that the NIO version will probably be more efficient because it doesn't reset the
Matcher to a new input source on each line of input as ReaderIter does.
Search WWH ::




Custom Search