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 =, 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 =;
    } catch (IOException e) {