java-如何计算段落之间的空格并从总行数中减去它们?

时间:2012-03-12 19:25:05

标签: java file count space lines

如果我读取文件在段落之间有空格,我如何计算空格并从总行数中减去它们?

public int countLinesInFile(File f){
    int lines = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader(f));

        while (reader.readLine() != null){
            lines++;    
        }
        reader.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return lines;
}

2 个答案:

答案 0 :(得分:3)

在每次迭代时,检查该行是否为空(或仅包含空格,具体取决于您的真实需求):

String line;
while ((line = reader.readLine()) != null) {
    if (line.isEmpty()) { // or if (line.trim().isEmpty()) {
        lines++;
    }
}

请:

  • 不要忽略异常。如果你不能在这里处理它们就扔掉它们
  • 在finally块中关闭阅读器

答案 1 :(得分:1)

查看某行是否为空:

 int blankLines = 0;
 String lineRead = "";
 while ( lineRead != null ){
       lineRead = reader.readLine();
       //on newer JDK, use lineRead.isEmpty() instead of equals( "" )
       if( lineRead != null && lineRead.trim().equals( "" ) ) {
        blankLines ++;
       }//if 
       lines++;    
 }//while

 int totalLineCount = lines - blankLines;

并尊重@JB Nizet的优秀建议:

/**
 * Count lines in a text files. Blank lines will not be counted.
 * @param f the file to count lines in.
 * @return the number of lines of the text file, minus the blank lines.
 * @throws FileNotFoundException if f can't be found.
 * @throws IOException if something bad happens while reading the file or closing it.
 */
public int countLinesInFile(File f) throws FileNotFoundException, IOException {
    BufferedReader reader = null;
    int lines = 0;
    int blankLines = 0;
    try {
            reader = new BufferedReader(new FileReader(f));

            String lineRead = "";
            while ( lineRead != null ){
               lineRead = reader.readLine();
               //on newer JDK, use lineRead.isEmpty() instead of equals( "" )
               if( lineRead != null && lineRead.trim().equals( "" ) ) {
                  blankLines ++;
               }//if 
               lines++;    
            }//while
    } finally {
       if( reader != null ) {
          reader.close();
       }//if
    }//fin
    return lines - blankLines;
}//met