|
How to apply Regular Expressions on the contents of a file |
|
|
This Java tip illustrates a method of applying Regular Expressions on the contents
of a file. The matching routines in java.util.regex require that the input be a
CharSequence object. This tip implements a method that efficiently returns the
contents of a file in a CharSequence object.
// Converts the contents of a file into a CharSequence
public CharSequence fromFile(String filename) throws IOException {
FileInputStream input = new FileInputStream(filename);
FileChannel channel = input.getChannel();
// Create a read-only CharBuffer on the file
ByteBuffer bbuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int)channel.size());
CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
return cbuf;
}
|
Here is sample code that uses the above method:
try {
// Create matcher on file
Pattern pattern = Pattern.compile("pattern");
Matcher matcher = pattern.matcher(fromFile("infile.txt"));
// Find all matches
while (matcher.find()) {
// Get the matching string
String match = matcher.group();
}
} catch (IOException e) {
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.