Java search word from text file


 

Java search word from text file

In this tutorial, you will learn how to search a word from text file

In this tutorial, you will learn how to search a word from text file

Java search word from text file

In this tutorial, you will learn how to search a word from text file and display data related to that word. Here, we have created a text file student.txt which consists of id, name and marks of few students. The example prompt the user to enter any student's name. It then scan the whole file to search the name and display the id and marks of the student. You can also search by id.

student.txt:

1 A 90 
2 B 30 
3 C 80 
4 D 99 
5 E 85 
6 F 25

Example:

import java.io.*;
import java.util.*;

public class SearchWord{
public static void main(String[]args) throws Exception{
	Scanner input=new Scanner(System.in);
	System.out.print("Enter name to find details: ");
	String word=input.next();
	File f=new File("c:/student.txt");
	BufferedReader freader = new BufferedReader(new FileReader(f));
	String s;
	while((s = freader.readLine()) != null) {
	String[] st = s.split(" ");
	String id = st[0];
	String name = st[1];
	String marks = st[2];
	if(name.equals(word)){
	System.out.println(id+" "+name+" "+marks);
	}
	}
  }
}

Output:

Enter name to find details: D
4 D 99

Ads