0

I am reading a file Java, using this code :

File file = new File(--path-);

Scanner reader= new Scanner(file);

while(reader.hasNext()){

    // i want to add here if reader.Next() == emptyline
    // I tried if reader.Next()=="" but it did not work.

}

thank you all

Perneel
  • 3,278
  • 7
  • 43
  • 65
Ali H
  • 11
  • 3
  • Have you tried `if(reader.hasNextLine())`? Please read [API Docs](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()) – BackSlash May 09 '14 at 08:25

3 Answers3

0

next() reads words and skips blanks.

I suggest you use

while(reader.hasNextLine()) {
    String line = reader.nextLine();
    if(line.isEmpty()) { ...
Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
0

try looking at http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

String line = reader.nextLine ();
while (line != null) {

  if (line.length () == 0) {
     System.out.println ("zero length line");
  }
  else {
    System.out.println (line);
  }
  line = reader.nextLine ();
}

or

while (reader.hasNextLine()) {

  line = reader.nextLine ();
  if (line.length () == 0) {
     System.out.println ("zero length line");
  }
  else {
    System.out.println (line);
  }

}
Scary Wombat
  • 43,525
  • 5
  • 33
  • 63
0

If you just need to read all the lines, you can simply use:

List<String> lines = Files.readAllLines(path, charset);
assylias
  • 310,138
  • 72
  • 642
  • 762