Java 换行字符数

Java 换行字符数,java,Java,我正在设计一个实用程序,计算单词和换行符的数量 我已经完成了计数任务,但我不知道如何计算文件中新行字符的数量 代码: System.out.println ("Counting Words"); InputStream stream = Run.class.getResourceAsStream("/test.txt"); InputStreamReader r = new InputStreamReader(stream); BufferedReader br = new Buffered

我正在设计一个实用程序,计算单词和换行符的数量

我已经完成了计数任务,但我不知道如何计算文件中新行字符的数量

代码:

System.out.println ("Counting Words"); 

InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);     
String line = br.readLine();
int count = 0;

while (line != null) {
    String []parts = line.split(" ");
    for( String w : parts){
        count++;        
    }
    line = br.readLine();
}

System.out.println(count);
测试


这是Java程序读取的简单文件

只需查看以下文字:

System.out.println ("Counting Words");       
InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);     
String line = br.readLine();
int word_count = 0;
int line_count = 0;

while (line != null) {
    String[] parts = line.split(" ");
    word_count += parts.length;
    line_count++;
    line = br.readLine();
}

System.out.println("Word count: " + word_count + " Line count: " + line_count);
for (char c : w.toCharArray()) {
    if (c == '\n') {
        numNewLineChars++;
    }
}

它位于您已有的for循环中。

在这里,使用类来计算和读取文本行可能是一个更好的选择。尽管这不是计算文件中行数的最有效方法(根据这一点),但它应该足以满足大多数应用程序的需要

从中选择readLine方法:

读一行文字。每当读取行终止符时,当前行号将递增。(行终止符通常是换行符“\n”或回车符“\r”)

这意味着当您调用LineNumberReader类的getLineNumber方法时,它将返回由readLine方法递增的当前行号

我在下面的代码中加入了一些注释来解释它

    System.out.println ("Counting ...");       
    InputStream stream = ParseTextFile.class.getResourceAsStream("/test.txt");
    InputStreamReader r = new InputStreamReader(stream);

    /*
     * using a LineNumberReader allows you to get the current 
     * line number once the end of the file has been reached,
     * without having to increment your original 'count' variable.
     */
    LineNumberReader br = new LineNumberReader(r);

    String line = br.readLine();

    // use a long in case you use a large text file
    long wordCount = 0;

    while (line != null) {
        String[] parts = line.split(" ");
        wordCount+= parts.length;
        line = br.readLine();
    }

    /* get the current line number; will be the last line 
     * due to the above loop going to the end of the file.
     */
    int lineCount = br.getLineNumber();

    System.out.println("words: " + wordCount + " lines: " + lineCount);

数一数,你读了多少行。数一数有什么问题?它似乎在记录行数。我想读取新的行字符,如“\n”。。。。