regex
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 thendecode(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()
andmatch()
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.io.FileInputStream; 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 = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size()); CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf); Matcher matcher = pattern.matcher(cbuf); while (matcher.find()) { String match = matcher.group(); System.out.println(match); } } }
This was an example of how to filter the content of a file using regular expressions in Java.