How can i detect BlankLine that Scanner has receiv

2019-06-05 18:30发布

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?

4条回答
Emotional °昔
2楼-- · 2019-06-05 18:32

After checking for an existing line with scanner.hasNextLine() method, you can use this condition:

String line = null;
if((line = scanner.nextLine()).isEmpty()){
   //your logic when meeting an empty line
}

and use the line variable in your logic.

查看更多
放我归山
3楼-- · 2019-06-05 18:33

You can simply check your scanner.nextLine() for a Newline "\n" (I mean "", because nextLine() does not read "\n" at the end of any line).. If its equal, it will be a blank line..

if (scanner.nextLine().equals("")) {
    /** Blank Line **/
}

BTW, there is a problem with your code: -

while(fileIn.hasNextLine()){          
         String line = fileIn.nextLine();
         String linename = fileIn.nextLine();
         String statusline = fileIn.nextLine();

You are assuming that your fileIn.hasNextLine() will confirm about the next three lines being not null.

Everytime you do a fileIn.nextLine() you need to check whether it's available or not.. Or you will get exception...

*EDIT: - O.o... I see there you have handled exception.. Then there will be no problem.. But still you should modify the above code.. It doesn't look pretty..

查看更多
倾城 Initia
4楼-- · 2019-06-05 18:38

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;
}
查看更多
戒情不戒烟
5楼-- · 2019-06-05 18:44

Try this...

while(scanner.hasNextLine()){

    if(scanner.nextLine().equals("")){

            // end of profile one...

       }

}
查看更多
登录 后发表回答