user868935
user868935

Reputation:

java- How do I count the empty spaces between paragraphs and subtract them from the total line count?

If I read a file the have empty spaces between paragraphs, how do I count the empty spaces and subtract them from the total line count?

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;
}

Upvotes: 0

Views: 1956

Answers (2)

Snicolas
Snicolas

Reputation: 38168

To see if a line is blank :

 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;

And to respect the excellent advices of @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

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691755

At each iteration, check if the line is empty (or contains only whitespace, depending on what your really want):

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

And please:

  • don't ignore exceptions. Throw them if you can't handle them here
  • close the reader in a finally block

Upvotes: 3

Related Questions