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.
public CharSequence fromFile(String filename) throws IOException {
FileInputStream input = new FileInputStream(filename);
FileChannel channel = input.getChannel();
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 {
Pattern pattern = Pattern.compile("pattern");
Matcher matcher = pattern.matcher(fromFile("infile.txt"));
while (matcher.find()) {
String match = matcher.group();
}
} catch (IOException e) {
}
java-tips.org
Thursday, October 29, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment