Create a Java program that reads the contents of a text file and stores it in an array of strings.
Then ask the user for words or phrases until you enter an empty text. Each time the user enters a word or phrase, it shows the lines that match the text, provided it is not empty.
vulputate himenaeos. Venenatis dapibus congue quis aptent tincidunt vivamus fermentum eu libero eros nullam varius curabitur, ligula et sem sapien eget fringilla euismod justo sociis malesuada aliquet leo pretium nullam ullamcorper vitae nostra mi
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class SearchTextLines { public static void main(String[] args) { String fileName = "input.txt"; List<String> lines = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; while ((line = br.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); return; } Scanner input = new Scanner(System.in); boolean exit = false; while (!exit) { System.out.print("Enter a word or phrase (leave empty to exit): "); String searchText = input.nextLine(); if (!searchText.isEmpty()) { for (String line : lines) { if (line.contains(searchText)) { System.out.println(line); } } } else { exit = true; } } input.close(); } }
Click here to view the exercise solution
Share it on your social media and challenge your friends to solve programming problems. Together, we can learn and grow.
The code has been successfully copied to the clipboard.
Continue improving your Java programming skills with our selection of practical exercises from the lesson. Click on Practice and challenge your knowledge!
Create a program in Java to request lines from the user and write them in a text file.
Create a Java program that reads a text file and displays all its lines on the screen.
Create a Java program that asks the user for lines until you press Enter.
Write a program in Java to read a text file and make a copy in another file by changing the lowercase letters to uppercase.
Create a program in Java to count the number of words stored in a text file.
Create a Java program that makes a copy of a text file but encrypted.
Create a Java program that makes a copy of a text file but reverse all its content.
Create a Java program that behaves like the Unix more command, you must display the contents of a text file and ask the user to press Enter every time the screen is full.
Practice with exercises in Java to manage text files. Learn how to create, update, and search text files in different ways.
Free programming course with practical exercises and solutions in C#. Start learning right now!
Take your Exercises C# lessons everywhere with our Android app. Download it now from Google Play
Own and third party cookies to improve our services. If you go on surfing, we will consider you accepting its use.