We can handle normal text file in java. For that, we must import java.io package. and create an object of the File class. This object can determine if a file exists or not. If exists, then we can easily do any thing with that file in the following example we find and count the occurrence of a pattern in a file. For that, we must create a file called test.txt in any directory [Here we put in in the same directory of the java file] and put some text in it.
import java.util.*;
import java.io.*;
public class FileSearch
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a File Name : ");
String fname=sc.nextLine();
System.out.print("Enter a Word : ");
String word=sc.nextLine();
int count=0;
try
{
File f=new File(fname);
if(f.exists())
{
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
String []words;
int i;
while ((line = br.readLine()) != null)
{
words=line.split(" ");
for(i=0;i<words.length;i++)
{
if(words[i].equals(word))
{
count++;
}
}
}
System.out.print("Frequency of the word \"" + word + "\" in the file " + fname + " are " + count);
}
else
{
System.out.print("File Not Found");
}
}
catch(Exception e)
{
System.out.print(e.toString());
}
}
}
Enter a File Name : test.txt
Enter a Word : You
Frequency of the word "You" in the file test.txt are 3