How to read text from a file between two given patterns in java8

I have one text file. I have to read contents between two given patterns.

for example lets I have a file names - datafromOU.txt

I have to need data from the pattern1 till pattern2.

pattern1 : "CREATE EXTR"
Pattern2 :";"

But problem is - file has multiple occurances of pattern2. So my requirement is to look for pattern1 and then search immediate occurance of pattern2 after the pattern1. I need to store this into one string and then process later.

Can you help me how to read data from pattern1 and immediate occurance of pattern2 into a string variable using java streams?

I use java8. Thanks a lot in advance.

Thanks.

Upvotes: 0

Views: 163

Answers (1)

Ashutosh Mishra
Ashutosh Mishra

Reputation: 89

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    
    static String getPatternFromString(String startPattern,String endPattern,String data) {
        int startIndex=data.indexOf(startPattern);
        data=data.substring(startIndex);
        int endIndex=data.indexOf(endPattern, startIndex + startPattern.length());
        data=data.substring(0,endIndex+1);
        return data;
    }
    
    public static void main(String[] args) throws IOException {
        File file1 = new File("C:\\Users\\amish\\Desktop\\partie.txt");
        String startPattern="CREATE EXTR";
        String endPattern=";";
        try (BufferedReader leBuffer1 = new BufferedReader(new FileReader(file1));) {
            StringBuilder everything = new StringBuilder();
            String line;
            while ((line = leBuffer1.readLine()) != null) {
                everything.append(line);
            }
            String data = everything.toString();
            data = data.trim();
            System.out.println(data);
            System.out.println(getPatternFromString(startPattern,endPattern, data));
            leBuffer1.close();
        } catch (FileNotFoundException exception) {
            System.out.println("File not found");
        }
    }
}

Upvotes: 1

Related Questions