 |
|
 |
| |
Developer on focus
Anton Zamov is a dipl. engineer with more than 6 years of active professional
experience and many awards ...
read more>>
|
|
 |
 |
 |
|
 |
|
 |
| |
|
How to Apply Regular Expressions on the Contents of a File?
|
The matching routines in java.util.regex require that the input be a CharSequence object. This example implements a method that efficiently returns the contents of a file in a CharSequence object.
// Converts the contents of a file into a CharSequence
// suitable for use by the regex package.
public CharSequence fromFile(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
FileChannel fc = fis.getChannel();
// Create a read-only CharBuffer on the file
ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
return cbuf;
}
Here is sample code that uses the 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) {
}
|
About the author of this programming example or tutorial:
Anton Zamov is a software engineer with more than6 years
of active experience in web and software development and design.
Anton Zamov has extensive experience and broad knowledgebase
in C# and JAVA programming and has created a lot of
running e-commerce systems, portals and content management
systems using PHP and other web development technologies.
For more information about Anton Zamov, you may visit the personal web site of
Anton Zamov.
|
|
|
 |
 |
 |
|
|