user3310883
user3310883

Reputation: 95

How to check if next line in text file is empty?

I want the program to find "[DesiredText]" and check if next line is empty, then if it is i want to take position of empty line. I saw few example but I doesn't work properly. All advices and clues are welcome.

BufferedReader br = new BufferedReader(new FileReader(file));

String line = null;

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

 if ((line.contains("[DesiredText]") && br.readLine().isEmpty())) {

              RandomAccessFile raf = new RandomAccessFile("D:\\Temp.txt","r");
              long position = raf.getFilePointer();
              pozycje.add(position);
              raf.close();


        }
}

Upvotes: 1

Views: 12214

Answers (3)

enterbios
enterbios

Reputation: 1755

You can create two RandomAccessFiles where the second one will be one line further than first one. Something like:

    RandomAccessFile first = new RandomAccessFile("D:\\Temp.txt","r");
    RandomAccessFile second = new RandomAccessFile("D:\\Temp.txt","r");

    String line;
    String nextLine = second.readLine();

    while (nextLine != null) {
        line = first.readLine();
        nextLine = second.readLine();

        if ((line.contains("[DesiredText]") && nextLine.isEmpty())) {
            pozycje.add(first.getFilePointer());
        }
    }

Upvotes: 0

NRJ
NRJ

Reputation: 1204

You could keep track of the length of the string+ newline char you have read so far, and once you get a blank line, the length variable should give you the position of the blank line.

Upvotes: 0

developerwjk
developerwjk

Reputation: 8659

Read the line, then check

   if("".equals(line))

Or if you don't want to count white-space:

   if("".equals(line.trim()))

Also, if you have a loop like while ((line = br.readLine()) != null) which is controlled by the value of br.readLine() you should not be calling br.readLine() again inside the loop. That may cause you to go past the end of the file inside the loop and get an error.

What you should do, is set a flag when you find line.contains("[DesiredText]") and then in the next iteration of the loop (the next line) you will check if the line is empty if that flag is set.

Upvotes: 2

Related Questions