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

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

System.out.println(count);

测试

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

4

3 回答 3

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);
于 2013-10-26T17:15:34.353 回答
0

看看里面的文字:

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

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

于 2013-10-26T17:17:50.153 回答
0

在这里使用LineNumberReader类来计算和读取文本行可能是一个更好的选择。虽然这不是计算文件中行数的最有效方法(根据这个问题),但对于大多数应用程序来说应该足够了。

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);
于 2013-10-26T18:00:10.440 回答