BufferedReader.readLine () returns null as a result

0

I am writing a method to count the number of lines in a text document in Java.

public int numeroLineas(FileReader re) throws IOException {

    String str;

    BufferedReader br = new BufferedReader(re);
    Vector<String> v = new Vector<String>();

    while ((str = br.readLine()) != null) {
        v.add(str);
    }

    if (v != null) {
        br.close();
    }

    System.out.println("Lineas: " + v.size());
    return v.size();
}

The While cycle can not be accessed because br.ReadLine () returns null .

The result in the console is always:

Lineas: 0
0
    
asked by Bryan Romero 02.08.2017 в 18:57
source

1 answer

1

The problem was solved when changing the FileReader parameter of the method to one of File type, it had two methods that were called in the main .

File file = new File("C:/Users/bryan/Desktop/Apelli.txt");

FileReader f = new FileReader(file);

    Lettura writer;
    writer= new Lettura ();
    System.out.println(writer.letteraOrdine(f));
    System.out.println(writer.numeroRighe(f));

The two used the same FileaReader, I do not know if that caused the conflict. The modified method:

public int numeroLineas(File f) throws IOException {

    String str;

    BufferedReader br = new BufferedReader(new FileReader(f));
    Vector<String> v = new Vector<String>();

    while ((br.readLine()) != null) {
        str = br.readLine();
        //System.out.println("str " + str);
        v.add(str);
    }

    if (v != null) {
        br.close();
    }

    System.out.println("Lineas: " + v.size());
    return v.size();
}

After having modified the methods, call them like this:

File file = new File("C:/Users/bryan/Desktop/Apelli.txt");

    Lettura writer;
    writer= new Lettura ();
    System.out.println(writer.letteraOrdine(file));
    System.out.println(writer.numeroRighe(file));

And it worked without problems.

    
answered by 02.08.2017 / 19:31
source