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,317
  • 7
  • 45
  • 66
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
  • 525,659
  • 79
  • 751
  • 1,130
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
  • 44,617
  • 6
  • 35
  • 64
0

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

List<String> lines = Files.readAllLines(path, charset);
assylias
  • 321,522
  • 82
  • 660
  • 783