Sunday, August 11, 2019

How to read a text file and search any specific word in java

This tutorial explains how to read a text file and search any specific word in java. In order to search any specific word from a text file, we need to first read text file. Here we have provided simple example for reading a text file and search any specific word from that.

How to read a text file and search any specific word in java

sample.txt
we are going to use below text file content using java code.
Simple Form Validation In Reactjs Example
Create a Dropdown Menu using ReactJS
Installing React Native on Windows Tutorial
Create Dropdown Menu In React Native
How To Customize Button In React Native
Facebook loading animation using CSS3
Facebook Style Chat Application with jQuery and CSS
Append Or Prepend HTML Using ReactJS
Create Ripple Animation Effect Using Css
Ripple Effect Animation On Button Click With CSS3

FileWordSearch.txt
package demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileWordSearch {

 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub

  String[] words = null; // Intialize the word Array

  // Creation of File Descriptor for input file
  File f1 = new File("sample.txt");

  // Creation of File Reader object
  FileReader fr = new FileReader(f1);

  // Creation of BufferedReader object
  BufferedReader br = new BufferedReader(fr);

  String s;
  String input = "Facebook"; // Input word to be searched
  int count = 0; // Intialize the word to zero

  // Reading Content from the file
  while ((s = br.readLine()) != null) {
   words = s.split(" "); // Split the word using space
   for (String word : words) {
    if (word.equals(input)) { // Search for the given word
     count++; // If Present increase the count by one
    }
   }
  }
  if (count != 0) { // Check for count not equal to zero
   System.out.println("The given word is present for " + count
     + " Times in the file");
  } else {
   System.out.println("The given word is not present in the file");
  }

  fr.close();

 }
}

Output:-
------------------


This is all about Java Program to Search for a given word in a File. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment