在java中读取文件时如何检测我们有一条线?

时间:2014-05-09 08:21:38

标签: java

我正在使用以下代码阅读文件Java:

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.

}

谢谢大家

3 个答案:

答案 0 :(得分:0)

next()读取单词并跳过空白。

我建议你使用

while(reader.hasNextLine()) {
    String line = reader.nextLine();
    if(line.isEmpty()) { ...

答案 1 :(得分:0)

尝试查看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 ();
}

while (reader.hasNextLine()) {

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

}

答案 2 :(得分:0)

如果您只需阅读所有行,您只需使用:

List<String> lines = Files.readAllLines(path, charset);