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
/Users/mayanksolanki/Desttop/Folder/
In Windows: ‘ \\ ‘ used instead of ‘ / ‘ to escape ‘ \ ‘ character. So the same directory is accessed as
\\Users\\mayanksolanki\\Desktop\\Folder\\
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 |
FileOutputStreamClass |
---|---|
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 class_name.java // 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 java.io.FileWriter; // 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’
Approach:
- 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
// Java Program to print all the // Strings that match a given // Pattern from a File // Importing Classes/Files import java.io.*; // 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!" ); writer.close(); // Success Message System.out.println( "Successfully wrote to the file.\n" ); } // Catch block to handle exception catch (IOException e) { // Catching any error System.out.println( "An error occurred." ); e.printStackTrace(); } // 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(match.group(0)); // 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. System.out.println( line.substring(start, end)); } } } } |
Output:
The above input is hardcoded input run on the terminal on mac in which:
- 1st line ‘javac file_name.java’ 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