Filter the content of a file using regular expressions

This is an example of how to filter the content of a file using regular expressions. Filtering the content of a file using regular expressions implies that you should:

  • Compile a given String regular expression to a Pattern, using compile(string regex) API method of Pattern.
  • Create a new FileInputStream with a given String path by opening a connection to a file.
  • Get the FileChannel object associated with the FileInputStream, with getChannel() API method of FileInputStream.
  • Create a ByteBuffer, using map(MapMode mode, long position, long size) API method of FileChannel that maps a region of this channel’s file directly into memory.
  • Create a CharBuffer, using forName(String charsetName) API method of Charset, newDecoder() API method of Charset and then decode(ByteBuffer in) API method of CharBuffer to decode the remaining content of a single input byte buffer into a newly-allocated character buffer.
  • Use matcher(CharSequence input) API method of Pattern to get a matcher that will match the given char buffer against this pattern.
  • Use find() and match() API methods of Matcher to get the matches of the the buffer with the pattern.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] argv) throws Exception {
    Pattern pattern = Pattern.compile("pattern");
    FileInputStream input = new FileInputStream("file.txt");
    FileChannel channel = input.getChannel();

    ByteBuffer bbuf =, 0, (int) channel.size());
    CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);

    Matcher matcher = pattern.matcher(cbuf);
    while (matcher.find()) {

String match =;


This was an example of how to filter the content of a file using regular expressions in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button