Search code examples
javastringfile-read

How to read data from file till I encounter an empty line


Is there a way I can read multiple lines from a text file until I encounter an empty line?

For example my text file looks like this:

text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text

//This is empty line

text2-tex2-text2-tex2-text2-tex2-text2-text2

Now, I want to input text-text... till the empty line into a string. How can I do that?


Solution

  • check below code, 1st i have read all the lines from text file, then i have check whether file contains any blank line or not, if it contains then i break the loop.

    A.text

    text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text

    text2-tex2-text2-tex2-text2-tex2-text2-text2

    import java.util.*;
    import java.io.*;
    
    public class Test {
        public static void main(String args[]){
            try (BufferedReader br = new BufferedReader(new FileReader("E:\\A.txt"))) {
                String line;
                while ((line = br.readLine()) != null) {
                    if(!line.isEmpty()){
                        System.out.println(line);
                    } else {
                        break;
                    }
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }