Open In App
Related Articles

Java Program to Print all the Strings that Match a Given Pattern from a File

Improve Article
Save Article
Like Article

Figure a way out to print all the strings that match a given pattern from a file. To get closer to the goal, concepts of files should be crystal clear so as to think out a way to print strings later on implementing the same to reach the final goal. So prior to dealing with the strings urgency is to discuss out file concepts. Once the file concepts are grasped strings dealing will be carried on.   Starting from scratch where no file is there in the directory.

Thought Process: FileConcepts + Strings

  • Step 1: Creation of file.
  • Step 2
    • Writing to the same file.
    • Condition check if the message is successfully written.
    • Indulging concepts for strings to the above-written file.
    • Displaying all the strings if matched with a given pattern in the above file.

File Concepts

Step 1: Creating a new file 

A File is an abstract path, it has no physical existence. It is only when “using” that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement.

Primary, in order to create a new file, inbuilt files and functions are used which definitely will throw Exceptions here playing it safe. So in order to deal with it, we will be using Exception Handling Techniques. Here, we will use one of them known as- try-catch block techniques. 

Secondary, additional work is simply we will be importing File Class for which we will be importing File Class.

Syntax: To import file library or Classes

import java.util.File ;

Syntax: To create a new file

File object_name = new File(Directory); 

Syntax: To specify a directory is different in different operating systems (suppose java file is in a folder named ‘Folder’ is created on desktop)

In Linux and Mac


In Windows: ‘ \\ ‘ used instead of  ‘ / ‘ to escape ‘ \ ‘ character. So the same directory is accessed as


There are two standards methods to create a new file either directly with the help of File class or indirectly with the help of FileOutputStream by creating an object of the file in both the approaches.

  • By using File Class
  • By using FileOutputStream Class

File Class


It is a class which is just a handle for   It is an output stream that can be written to FileOutputStream JavaDoc
Method: File.createNewFile()

Method: FileOutputStream 

Example: echo > myFile.txt

It is used for those objects which are not having physical existence  It is used for those objects which are already existing

Both classes provide some methods which are mainly used to do operations regarding file. For example, to create, to write, to compare two path names, to check whether a specific file is present or not, and many more. To understand this topic, first, considering one example for both approaches.

  • Terminal Command used to compile any java code on the machine
  • Terminal Command used to Run any java code on the machine
    • javac // For Compilation
    • java class_name       // For Execution

Terminal of Mac operating system will be used for implementation and providing an output of accessing the directory

Directory Used : /Users/mayanksolanki/Desktop/Folder/ 

Step 2: Write over a file: Now 1st step is over. moving onto next now the file is to be written

In order to do so, a class need to be imported called ‘FileWriter

Syntax: For importing class to write

import;    // Class imported to write over a file

Syntax: To write over which file

FileWriter myWriter = new FileWriter("filename.txt");

Syntax: To write on a file

myWriter.write("Insert the string here which later is supposed to be checked present or not");

Step 3: Printing strings in the file:

In order to do so, a class needs to be imported called ‘Util.regex‘ and the method used ‘Patternname.matcher()‘ method of this class only to match the strings present in a file.

Pattern pattern_name = Pattern.compile("[A-Za-z][a-z]+");

Hence now proposing out the approach for demo class named ‘test.txt’


  • Read the file.
  • Define the pattern you want to search for.
  • Look for the pattern in each line of the file.

Considering an example to discuss the above by implementation alongside in order to check out internal working:


// Java Program to print all the
// Strings that match a given
// Pattern from a File
// Importing Classes/Files
// Importing Special Class 
// for matching patterns
import java.util.regex.*;
public class GFG {
    // Main driver method
    public static void main(String[] args)
        throws IOException
        // Try block for detecting exception
        try {
            // Creating a file
            FileWriter writer = new FileWriter("test.txt");
            // Writing in file
            writer.write("Writing in the test file!");
            // Success Message
                "Successfully wrote to the file.\n");
        // Catch block to handle exception
        catch (IOException e) {
            // Catching any error
            System.out.println("An error occurred.");
        // FileReader
        BufferedReader read = new BufferedReader(
            new FileReader("test.txt"));
        // The regex pattern
        Pattern pattern = Pattern.compile("[A-Za-z][a-z]+");
        System.out.println("Matched Content:");
        // For each line of input, try matching the pattern
        String line;
        while ((line = read.readLine()) != null) {
            // For each match in the 
            // line, extract and print it
            Matcher match = pattern.matcher(line);
            while (match.find()) {
                // One method:
                // System.out.println(;
                // Another method:
                // Get the starting position of the text
                int start = match.start(0);
                // Get ending position
                int end = match.end(0);
                // Print whatever matched.
                    line.substring(start, end));




The above input is hardcoded input run on the terminal on mac in which:


  • 1st line ‘javac’ compiles the file in the directory where the filename is GFG
  • 2nd line ‘java  file_name’ represents the above code is executed
  • 3rd line till last is the hardcoded output of strings matched in the created class ‘test.txt’ as a sample class for the above code


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 29 Oct, 2021
Like Article
Save Article
Similar Reads
Related Tutorials