DrNutsu DrNutsu - 7 months ago 15
Java Question

How can i detect BlankLine that Scanner has receive?

I want to get data form text files ,and I use Scanner to get data form text file.
It's profile save pattern

name
status
friend
friend
.
.
(Blank line)


Blank Line is separate each profile.(friend will looping till next line is a Blank Line)

john
happy
james

james
sad
john


And i code to get file form text like this

try{
Scanner fileIn = new Scanner(new FileReader("testread.txt"));
while(fileIn.hasNextLine()){
String line = fileIn.nextLine();
String linename = fileIn.nextLine();
String statusline = fileIn.nextLine();
println("name "+linename);
println("status "+statusline);
while(/*I asked at this*/)){
String friendName = fileIn.nextLine();
println("friend "+friendName);
}
}
}catch(IOException e){
println("Can't open file");
}


What condition that I should use to detect blank line between profile?

Answer

You can implement custom function like below which will return you nextLine if it is not empty.

 public static String skipEmptyLines(Scanner fileIn) {
    String line = "";
    while (fileIn.hasNext()) {
        if (!(line = fileIn.nextLine()).isEmpty()) {
            return line;
        }
    }
    return null;
}
Comments