Share on Google+Share on Google+

Search word from text file using Java

In this section, we are going to search a word from the text file using java Program.

How to Search word from text file using Java

In this section, we are going to search a word from the text file. For this, we have created a swing button. On clicking, it will open another window that will ask the user to enter name. When the user typed his/her name, it will check the name in the text file. To check the name, we have stored all the data into ArrayList and then terator class iterates over it. If the name exists, it will print the name and corresponding age from the text file.

Here is the code:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class SearchName extends JFrame {
	static String name;
	static String age;

	public SearchName() {

	public SearchName(String name, String age) { = name;
		this.age = age;

	public String getName() {
		return name;

	public String getAge() {
		return age;

	public static void main(String[] args) {
		SearchName search = new SearchName();
		JButton button = new JButton("Search");
		JPanel panel = new JPanel();
		search.setSize(300, 60);
		ActionListener actionListener = new ActionListener() {
			public void actionPerformed(ActionEvent actionEvent) {
				String n = JOptionPane.showInputDialog(null, "Enter name");
				try {
					FileInputStream fstream = new FileInputStream(
					DataInputStream in = new DataInputStream(fstream);
					BufferedReader br = new BufferedReader(
							new InputStreamReader(in));
					String strLine;
					ArrayList list = new ArrayList();
					while ((strLine = br.readLine()) != null) {
					Iterator itr;
					for (itr = list.iterator(); itr.hasNext();) {
						String str =;
						String[] splitSt = str.split(" ");
						String id = "", name = "", age = "";
						for (int i = 0; i < splitSt.length; i++) {
							id = splitSt[0];
							name = splitSt[1];
							age = splitSt[2];
						ArrayList alist = new ArrayList();
						alist.add(new SearchName(name, age));
						for (SearchName s : alist) {
							if (n.equals(s.getName())) {
								System.out.println("Name Age ");
										.print(s.getName() + " " + s.getAge());
				} catch (Exception e) {




Posted on: October 30, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null