newbieprogrammer
newbieprogrammer

Reputation: 868

Java read text file and search for a line

I have the following code, which read thru the files and search for the line that start with subject and print out that line. But I only want to read the first line that contain the 'Subject' but currently it getting all the line that start with 'Subject' how can I configure such that it search for the first 'Subject' and print that one line ?

            br = new BufferedReader(new FileReader("FilePath"));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while ((line = br.readLine()) != null) {

                if (line.startsWith("Subject ")) {
                    System.out.println(line);

                }
            }

Upvotes: 1

Views: 2446

Answers (4)

Sarz
Sarz

Reputation: 1976

Using ArrayList you can save each line start with "Subject" and can traverse all of them you can use it according to your requirements

    ArrayList<String> list = new ArrayList<String>(); 
    br = new BufferedReader(new FileReader("FilePath"));
    StringBuilder sb = new StringBuilder();
    String line = "";

    while ((line = br.readLine()) != null) {

        if (line.startsWith("Subject ")) {
            list.add(line);

        }
    }
    System.out.println(list.get(0);

Upvotes: 0

user3215733
user3215733

Reputation:

You are not stopping your loop, so it will fetch until last line;

try this

 if (line.startsWith("Subject ")) {
   System.out.println(line);
   break; // break the lop on success match
 }

Upvotes: 0

Rushikesh Thakkar
Rushikesh Thakkar

Reputation: 723

You should try to use Regular Expressions to find all the occurrences of desired Pattern i.e. something like "Subject*\n" in your case. Check out this very good tutorial on Regex: www.vogella.com/tutorials/JavaRegularExpressions/article.html

Upvotes: 0

Vishal Santharam
Vishal Santharam

Reputation: 2023

Use break; statement,

br = new BufferedReader(new FileReader("FilePath"));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while ((line = br.readLine()) != null) {

                if (line.startsWith("Subject ")) {
                    System.out.println(line);
                    break;
                }
            }

Upvotes: 2

Related Questions