Как рассчитать пустые места между абзацами и вычесть их из общего числа строк? - PullRequest
0 голосов
/ 12 марта 2012

Если я читаю файл с пустыми пробелами между абзацами, как мне подсчитать пустые пробелы и вычесть их из общего числа строк?

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 ]

3 голосов
/ 12 марта 2012

На каждой итерации проверяйте, является ли строка пустой (или содержит только пробелы, в зависимости от того, что вы действительно хотите):

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

И, пожалуйста:

  • don 'т игнорировать исключения.Бросьте их, если вы не можете справиться с ними здесь
  • закройте читатель в блоке finally
1 голос
/ 12 марта 2012

Чтобы узнать, не заполнена ли строка:

 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
...