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