This section illustrates you how to search a string in a file content.
Applying Regular Expressions on the Contents of a File
This section illustrates you how to search a string in a file content. Following takes the file name from which the given string/text has to be searched. File name must be text file (with ".txt" extension). This program is followed only for the text file.
Code Description:
FileChannel:
This is the class of java.nio.channels.*; package. This class is used
for reading, writing and manipulating a file. Multiple threads use the file
channel concurrently. And file channel is safe for that purposes.
new FileInputStream(filename).getChannel():
Above method returns the unique instance of the FileChannel which is
associated with the object of the FileInputStream class. The constructor of the
FileInputStream class take a file name for which the object of the FileChannel
has to be created.
CharBuffer:
This is the class of the java.nio package. This class is used for
performing many type of operation on the character buffer. Here in the following
program, the object of the CharBuffer class has been created by using the forname()
method of the Charset class.
Charset:
This is the class of java.nio.charset package which provides the
facilities for mapping between 16-bit Unicode characters sequences and the
sequences of bytes. This class is also used for creating decoders and encoders
for reading, writing and manipulating files. It defines a static method for
check whether the specified charset is supported or not for the JVM (Java
Virtual Machine).
Charset.forname("8859_1").newDecoder().decode(fileChannel.map(FileChannel.MapMode.READ_ONLY,
0, (int)fileChannel.size())):
Above code creates a instance of the CharBuffer class. This code has
been used many other methods and fields as parameter of the forname()
method of the Charset class. This method takes a charset specified as
"8859_1".
Charset.newDecoder():
Above method of the Charset class creates a decoder for the specified
charset.
Charset.decode():
Above method of the Charset class is used to decode bytes of the
specified charset into Unicode characters.
Here is the code of the program:
import java.util.regex.*;
|