换行符数

时间:2013-10-26 17:11:11

标签: 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 count = 0;

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

System.out.println(count);

测试

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

看看里面的话:

for (char c : w.toCharArray()) {
    if (c == '\n') {
        numNewLineChars++;
    }
}

哪个进入你已经拥有的for循环。

答案 2 :(得分:0)

使用LineNumberReader类来计算和读取文本行可能是更好的选择。虽然这不是计算文件中行的最有效方法(根据此question),但它应该足以满足大多数应用程序。

LineNumberReader获取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);