Сделал wc-программу на Java, но она не будет учитывать символ конца строки

Итак, я в значительной степени завершил (я думаю) свою программу wc на Java, которая берет имя файла из пользовательского ввода (даже несколько) и подсчитывает строки, слова, байты (количество символов) из файла. Для целей тестирования были предоставлены 2 файла в формате .dat, которые можно было прочитать из командной строки dos/linux. Все работает правильно, за исключением подсчета, когда в конце строки есть символы \n или \r\n. Это не будет учитываться. Пожалуйста помоги?

import java.io.*;
import java.util.regex.Pattern;

public class Prog03 {


private static int totalWords = 0, currentWords = 0;
private static int totalLines =0, currentLines = 0;
private static int totalBytes = 0, currentBytes = 0;

public static void main(String[] args) {


    System.out.println("This program determines the quantity of lines,                                    words, and bytes\n" +
"in a file or files that you specify.\n" +
"\nPlease enter one or more file names, comma-separated: ");

        getFileName();

         System.out.println();

} // End of main method.


public static void countSingle (String fileName, BufferedReader in) {

    try {

        String line;

        String[] words;

        //int totalWords = 0;

        int totalWords1 = 0;

        int lines = 0;

        int chars = 0;

        while ((line = in.readLine()) != null) {

            lines++;
            currentLines = lines;

            chars += line.length();
            currentBytes = chars;

            words = line.split(" ");

            totalWords1 += countWords(line);
            currentWords = totalWords1;

        } // End of while loop.

        System.out.println(currentLines + "\t\t" + currentWords + "\t\t" +     currentBytes + "\t\t"
                + fileName);

    } catch (Exception ex) {

        ex.printStackTrace();

    }
}

public static void countMultiple(String fileName, BufferedReader in) {

    try {

        String line;

        String[] words;

        int totalWords1 = 0;

        int lines = 0;

        int chars = 0;

        while ((line = in.readLine()) != null) {

            lines++;
            currentLines = lines;

            chars += line.length();
            currentBytes = chars;

            words = line.split(" ");

            totalWords1 += countWords(line);
            currentWords = totalWords1;


        } // End of while loop.
        totalLines += currentLines;            
        totalBytes += currentBytes;
        totalWords += totalWords1;

    } catch (Exception ex) {

        ex.printStackTrace();

    }

} // End of method count().

private static long countWords(String line) {

    long numWords = 0;

    int index = 0;

    boolean prevWhitespace = true;

    while (index < line.length()) {

        char c = line.charAt(index++);                

        boolean currWhitespace = Character.isWhitespace(c);

        if (prevWhitespace && !currWhitespace) {

            numWords++;

        }

        prevWhitespace = currWhitespace;

    }

    return numWords;

} // End of method countWords().

private static void getFileName() {        

    BufferedReader in ;        

      try {

    in = new BufferedReader(new InputStreamReader(System.in));

        String fileName = in.readLine();

        String [] files = fileName.split(", ");

          System.out.println("Lines\t\tWords\t\tBytes" + 
                "\n--------\t--------\t--------");

        for (int i = 0; i < files.length; i++) {
        FileReader fileReader = new FileReader(files[i]);

        in = new BufferedReader(fileReader);

        if (files.length == 1) {
            countSingle(files[0], in);
            in.close();
        }
        else {
        countMultiple(files[i], in);  
            System.out.println(currentLines + "\t\t" + 
                    currentWords + "\t\t" + currentBytes + "\t\t"
                + files[i]);
        in.close();
        }
        }    
        if (files.length > 1) {
          System.out.println("----------------------------------------" + 
                "\n" + totalLines + "\t\t" + totalWords + "\t\t" +     totalBytes + "\t\tTotals");
        }
      }

      catch (FileNotFoundException ioe) {
        System.out.println("The specified file was not found. Please recheck   "
                + "the spelling and try again.");

        ioe.printStackTrace();

    } 

       catch (IOException ioe) {

                ioe.printStackTrace();

            }


}
} // End of class

это вся программа, если кто-то помогает, нужно что-то увидеть, однако здесь я подсчитываю длину каждой строки в строке (и я предполагал, что символы eol будут частью этого подсчета, но это не так. )

  public static void countMultiple(String fileName, BufferedReader in) {

    try {

        String line;

        String[] words;

        int totalWords1 = 0;

        int lines = 0;

        int chars = 0;

        while ((line = in.readLine()) != null) {

            lines++;
            currentLines = lines;

            **chars += line.length();**
            currentBytes = chars;

            words = line.split(" ");

            totalWords1 += countWords(line);
            currentWords = totalWords1;


        } // End of while loop.
        totalLines += currentLines;            
        totalBytes += currentBytes;
        totalWords += totalWords1;

    } catch (Exception ex) {

        ex.printStackTrace();

    }

}

person Camdeazy    schedule 24.09.2015    source источник


Ответы (2)


BufferedReader всегда игнорирует символ новой строки или разрыва строки. Невозможно сделать это с помощью readLine().

Вместо этого вы можете использовать метод read(). Но в этом случае вы должны читать каждый символ отдельно.

person Rehman    schedule 24.09.2015
comment
Могу ли я сделать что-то вроде chars += in.read(); if (in.read() == ' ' chars-=1? - person Camdeazy; 24.09.2015
comment
вы не можете сделать chars += in.read() , потому что in.read() возвращает ascii-код прочитанного символа. Итак, что вы можете сделать, это поставить галочку на перевод строки (как вы сказали в своем комментарии), например: if (in.read() == 10) chars-=1; где 10 — это ascii-код перевода строки. - person Rehman; 24.09.2015

просто комментарий, чтобы разделить строку на слова, недостаточно разделить на основе одного пробела: line.split(" "); вы пропустите, если между словами есть несколько пробелов или табуляций. лучше сделать разделение на любой символ пробела line.split("\\s+");

person Sharon Ben Asher    schedule 24.09.2015
comment
Спасибо за инфу, не знал - person Camdeazy; 24.09.2015
comment
Я пытался использовать это, но он все равно читает только один байт. Я вставил туда вкладку, а счет увеличился только на 1, что я делаю не так? - person Camdeazy; 24.09.2015
comment
он все еще читает что как один байт? вы ставите вкладку где? что не работает? подробней с примерами... - person Sharon Ben Asher; 24.09.2015
comment
Пробовал использовать line.split(\\s+) вместо просто line.split(). Я добавил вкладку в начало и в середину файла sample.txt, созданного для целей тестирования. - person Camdeazy; 24.09.2015
comment
вы не считаете слова с помощью команды split. на самом деле вы ничего не делаете с массивом String[], который является результатом разделения. Вы используете свой собственный написанный метод countWords(), который делает что-то совершенно другое. - person Sharon Ben Asher; 08.10.2015