Applying Regular Expressions on the Contents of a File : ByteBuffer « File Input Output « Java

Applying Regular Expressions on the Contents of a File

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 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 =, 0, (int) fc.size());
    CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
    return cbuf;

  public static void main(String[] argv) throws Exception {
    // 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 =;


Related examples in the same category

1.View buffers
2.Use NIO to read a text file.
3.Create a read-only memory-mapped file
4.Create a read-write memory-mapped file
5.Create a private (copy-on-write) memory-mapped file.
6.use FileChannel and ByteBuffer
7.Fast Copy File
8.A ByteBuffer is a fixed-capacity buffer that holds byte values.
9.Create a ByteBuffer using a byte array
10.Create a non-direct ByteBuffer with a 10 byte capacity
11.Create a direct (memory-mapped) ByteBuffer with a 10 byte capacity.
12.Get the ByteBuffer's capacity
13.Use the absolute get().
14.Set the position
15.Use the relative get()
16.Get remaining byte count in a ByteBuffer
17.Set the limit for ByteBuffer
18.This convenience method sets the position to 0
19.Putting Bytes into a ByteBuffer
20.Converting Between a ByteBuffer an a Byte Array
21.Retrieve bytes between the position and limit
22.Retrieve all bytes in the buffer
23.Get and Set char type data in a ByteBuffer
24.Get and Set short type data in a ByteBuffer
25.Get and Set int type data in a ByteBuffer
26.Get and Set long type data in a ByteBuffer
27.Get and Set float type data in a ByteBuffer
28.Get and Set double type data in a ByteBuffer
29.Create a character ByteBuffer
30.Create a short ByteBuffer
31.Create an integer ByteBuffer
32.Create a long ByteBuffer
33.Create a float ByteBuffer
34.Create a double ByteBuffer
35.Get a substring
36.Using a ByteBuffer to Store Strings
37.Get default byte ordering
38.Put a multibyte value
39.Set to little endian
40.Determining If a ByteBuffer Is Direct
41.Reading from a Channel with a ByteBuffer
42.Writing and Appending a ByteBuffer to a File
43.Convert interchangeably between a ByteBuffer and a byte array
44.Create a ByteBuffer
45.Put bytes into a ByteBuffer
46.How to get bytes from a ByteBuffer
47.Write with ByteBuffer