Pergunta

I am new in this superb place. I got help several times from this site. I have seen many answers regarding my question that was previously discussed but i am facing problem to count the number of characters using FileReader. It's working using Scanner. This is what i tried:

class CountCharacter
{
public static void main(String args[]) throws IOException
{
    File f = new File("hello.txt");
    int charCount=0;
    String c;
    //int lineCount=0;
    if(!f.exists())
    {
        f.createNewFile();
    }
     BufferedReader br = new BufferedReader(new FileReader(f));

while ( (c=br.readLine()) != null) {
String s = br.readLine();
charCount = s.length()-1;
charCount++;


}
System.out.println("NO OF LINE IN THE FILE, NAMED " +f.getName()+ " IS " +charCount);
}
}`
Foi útil?

Solução

It looks to me that each time you go through the loop, you assign the charCount to be the length of the line that iteration of the loop is concerned with. i.e. instead of charCount = s.Length() -1; try charCount = charCount + s.Length();

EDIT:

If you have say the document with the contents "onlyOneLine"

Then when you first hit the while check the br.readLine() will make the BufferredReader read the first line, during the while's code block however br.readLine() is called again which advances the BufferredReader to the second line of the document, which will return null. As null is assigned to s, and you call length(), then NPE is thrown.

try this for the while block

while ( (c=br.readLine()) != null) { charCount = charCount + c.Length(); }

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top