Home Tutorial Java Core Java search word from text file

 
 

Share on Google+Share on Google+
Java search word from text file
Posted on: November 29, 2012 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java search word from text file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 29, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com