用Java读取文件时检测空行

时间:2016-04-22 01:17:58

标签: java

所以我在阅读文件时遇到了问题。使用BufferedRead我的代码很简单。我的文字由标题和正文组成,如下所示:

>Header1
This is body1 line1
This is body1 line2
>Header2
This is body2 line1
This is body2 line2
This is body2 line3
This is body2 line4

所以基本上,我检查每一行是否是标题,然后根据标题和正文的过程处理它。

try{
   FileReader file = new FileReader("file1.txt");
   BufferedReader br = new BufferedReader(file);
   String line;
   while((line=br.readLine()!=null && line.length()>0){
      if(checkHeader(line)){
         ProcessHeader(line);
      }else{
         ProcessBody(line);
      }
   }
}

问题是,我意识到因为这是来自服务器的可下载文件,有时文件随机有空行。例如,在10 Header和body之后,有空格。下一个空格可能在15个标题/正文之后。它会变成如下:

>Header1
This is body1 line1
This is body1 line2
>Header2
This is body2 line1
This is body2 line2
This is body2 line3
This is body2 line4
.<not blank line>
.<not blank line>
.<not blank line>
>Header10
Body10 line1
Body10 line2

>Header11
Body11 line1
Body11 line2
.<not blank line>
.<not blank line>
.<not blank line>
>Header 25
Body25 line1
Body25line2

>Header 26
.<not blank line>
.<not blank line>
...

我怎样才能检测到这样的空行,因为目前我的while循环会在找到空行后停止?我该如何检查文件的结尾?谢谢。

3 个答案:

答案 0 :(得分:2)

我建议您查看Files.readAllLines()方法。它返回一组行。然后,您可以轻松地遍历集合并检查每一行,看它是否等于空字符串。

https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29

这样的事情:

List<String> lines = Files.readAllLines(myfilepath);
for(String line : lines) {
 if (line.trim().isEmpty())
  continue;
 else if ( //etc. you can process each line however you want.
}

答案 1 :(得分:1)

Files.readAllLines会将整个文件加载到内存中,这可能会引发一些异常。我建议用BufferedReader手动解析文件,这样你就可以一次读取整行。

// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
    if (strLine.isEmpty()){
        // Do whatever you need to do when the empty line is found
    }

//Close the input stream
br.close();

答案 2 :(得分:0)

只需移动length() check内的while loop并反转检查,以便让程序跳过空白行。

像这样:

try{
   FileReader file = new FileReader("file1.txt");
   BufferedReader br = new BufferedReader(file);
   String line;
   while((line=br.readLine()!=null){
      if(line.length() == 0) {
         continue;
      }

      if(checkHeader(line)){
         ProcessHeader(line);
      }else{
         ProcessBody(line);
      }    
   }
}