简体   繁体   English

使用Java计算文件中的单词和换行符?

[英]Counting Words and Newlines In A File Using Java?

I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example. 我正在编写一个小型的Java应用程序,它将在文本文件中扫描特定单词的任何实例,并且需要具有一项功能,该功能可以报告该单词的实例在文件中的第14个单词,在第三行, 例如。

For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\\n) character and then incerement a line variable that i created: 为此,我尝试使用以下代码,我认为该代码将检查输入是否为换行符(\\ n),然后确定我创建的行变量:

FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;

int lines = 1;

while ((strLine = buffRead.readLine()) != null)
{
    if(strLine.contains(newLines))
    {
        System.out.println("Line Found");
        lines++;
    }
}
System.out.println("Total Number Of Lines In File: " + lines);

This does not work for, it simply display 0 at the end of this file. 这不适用于此,它仅在该文件的末尾显示0。 I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file. 我知道数据会在while循环中放入strLine中,就像我稍微更改代码以输出该行一样,它已成功从文件中获取每一行。

Would anyone happen to know the reason why the above code does not work? 会有人偶然知道以上代码无法正常工作的原因吗?

Read the javadocs for readLine . 阅读javadocs中的readLine

Returns: A String containing the contents of the line, not including any line-termination characters , or null if the end of the stream has been reached 返回:包含行内容的String, 不包含任何行终止符 ;如果已到达流的末尾,则返回null

readLine() strips newlines. readLine()删除换行符。 Just increment every iteration of the loop. 只需增加循环的每次迭代。 Also, you're overcomplicating your file reading code. 另外,您也使文件读取代码过于复杂。 Just do new BufferedReader(new FileReader("src/file.txt")) 只需执行new BufferedReader(new FileReader("src/file.txt"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM