Search in file Learn programming Java

Lesson:

Dynamic Memory Management


Exercise:

Search in file 16


Objetive:

Create a program to read a text file and ask the user for sentences to search in it.

It will read the whole file, store it in an ArrayList, ask the user for a word (or sentence) and display all the lines that contain such word. Then it will ask for another word and so on, until the user enters an empty string.


Code:

package Contains;
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		java.io.FileReader myfile = new java.io.FileReader("text.txt");
	java.io.BufferedReader myfileBufferedReader = new java.io.BufferedReader(myfile);

		try
		{
			ArrayList list = new ArrayList();
			String line;
			do
			{
				line = myfileBufferedReader.readLine();
				if (line != null)
				{
					list.add(line);
				}
			} while (line != null);
			myfile.close();

			String sentence;
			boolean exit = false;

			do
			{
				System.out.print("Enter word or sentence: ");
				sentence = new Scanner(System.in).nextLine();

				if (sentence.equals(""))
				{
					exit = true;
				}
				else
				{
					for (int i = 0; i < list.size(); i++)
					{
						String sentenceList = (String)list.get(i);

						if (sentenceList.contains(sentence))
						{
							System.out.println(sentenceList);
						}
					}
				}
			} while (!exit);

		}
		catch (RuntimeException e)
		{
			System.out.println("Error, " + e.getMessage());
		}
	}
}