0
我已经编写了以下代码来计算文件中的行数,字符数和单词数。 我已经使用了BufferedReader。使用缓冲读取器时发生错误
import java.io.*;
class FileCount
{
public static void main(String args[]) throws Exception
{
FileInputStream file=new FileInputStream("sample.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(file));
int i;
int countw=0,countl=0,countc=0;
do
{
i=file.read();
if((char)i==("\t"))
countw++;
else if((char)i=="\n")
countl++;
else
countc++;
}while(i!=-1);
System.out.println("Number of words"+countw);
System.out.println("Number of lines"+countw);
System.out.println("Number of characters"+countc);
}
}
的问题是,我必须只使用缓冲reader.I知道我们不能比较字符和字符串,我在我的代码做了。 有没有其他出路的代码?
我对InputStreamReader和FileInputStream不是很了解,但它看起来像是在尝试使一个已经是流的新流。我可能错了,但也许尝试使用br.read()而不是file.read()。此外,它看起来像你正在尝试通过每个字符,但你一次阅读多个字符。尝试比较每个角色,而不仅仅是整个事情。 – 2013-02-24 19:37:07
@lonnez - Java IO中流和包装器的包装是正常的(装饰器宠物)。这种用法并不完全正确,但不像你似乎暗示的那样。 – 2013-02-24 19:42:42