×
FREE ASSISTANCE FOR THE INQUISITIVE PEOPLE
Tutorial Topics
X
softetechnologies
Java String Programs - Part 1 WBUT : MCA 5th Semister - Java - 2009
File Handling In Java - Examples - Java
4736    Arnab De    31/07/2017

File Handling in JAVA

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.

text file
Test.txt

Write a program that takes a file name and a search string from the user. If the search string occurs in the file, then it counts the number of occurrences of the string. ( Assume that search pattern can exist more than two times in a line ). [WBUT MCA JAVA 2011]

softetechnologies
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());
}
}
}
softetechnologies

Output:

Enter a File Name : test.txt
Enter a Word : You
Frequency of the word "You" in the file test.txt are 3

marked text file
Test.txt
Java String Programs - Part 1 WBUT : MCA 5th Semister - Java - 2009
softetechnologies
Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
Enter New Comment
Comment History
No Comment Found Yet.
Albert Einstein
Pure mathematics is, in its way, the poetry of logical ideas.
Albert Einstein
2190
60.53
Today So Far
Total View (Lakh)
softetechnologies
26/05/2018     44697
01/01/2018     36866
25/06/2018     36808
28/06/2017     34888
02/08/2017     33478
01/08/2017     27832
06/07/2017     27605
15/05/2017     27175
14/07/2017     22932
11/09/2018     21655
softetechnologies