简体   繁体   中英

java.util.Scanner doesn't read empty line

I wrote a .txt file in which each line has a meaning - even an empty one. Scanner's methods next() and nextLine() do not recognize the empty line and jump right to the line with text. I'm wondering if there is a way for the scanner to consider all lines of text regardless the content.

I don't want to use BufferedReader because I'm working with very small tokens each time.

static final String fileName = "temp.txt";
    try {
            //System.out.println(Jsoup.connect(url).get());
            Document document = Jsoup.connect(url).get();
            FileWriter fileWriter = new FileWriter(fileName);

            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            Elements names = document.select("[id^=CZ]");
            for (Element name : names) {
                bufferedWriter.write(name.text());
                bufferedWriter.write(System.lineSeparator() + System.lineSeparator());
                System.out.println(name.text() + '\n');
            }
            bufferedWriter.close();
           Scanner in = new Scanner(new File(fileName));
           in.next();
           String s = names.first().text();
           String h = in.next();

           ...

At this point Strings s & h should be equal.

The document the scanner is reading starts with an empty line and goes like this:

asdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkdsasdkjasjkdajkdahkdjahdjadhkahdajkdajkds

Again, I have a dynamic file that might have first line empty and when I compare String s with String h they DO NOT equal. nextLine() and next() skip over the first line while it is still a valid element.

nextLine() is the method that you need. Unlinke next() , it does not skip ahead through newlines and white space.

Run this example ( demo )

Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
    String s = sc.nextLine();
    System.out.println("'"+s+"'");
}

on input with empty lines to see that these lines are preserved:

'quick brown'
''
'fox jumps'
'over'
''
'the'
''
'lazy dog'

next() method reads tokens seperated by whitespaces or newline characters on other hand nextLine() reads lines seperated by newline charater.

You can try this:

Scanner scan = new Scanner(file);
while(scan.hasNextLine()){
    System.out.println(scan.nextLine());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM