Reputation: 363
I have written the following code to count number of lines,characters and words from a file. I have used 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);
}
}
The problem is that i have to only use buffered reader.I know we can not compare char and String which i have done in my code. is there any other way out to this code?
Upvotes: 0
Views: 285
Reputation: 28687
First, you need to actually read from the BufferedReader
- but as provided above, you're really ignoring that you even have this. Instead of file.read()
, you need to do br.read()
.
Part of the problem that you maybe already observed with your current approach is that you're probably missing characters when reading directly from file
, after having attached a BufferedReader
to it. The BufferedReader
may pre-read characters from the stream to fill the buffer - so reading directly from file
will cause those characters to be missed.
Then, you're correct, you can't compare against characters and Strings - so compare against characters:
if((char)i == ('\t'))
countw++;
else if((char)i == '\n')
countl++;
Once you get these issues out of the way, there are other issues that I expect you'll find - but hopefully this will be enough to get you started. (For example, are your words really separated by tab characters - or do you want to be looking for spaces, etc.?)
Upvotes: 2