Duplicate files when reading text file line by line with java

0

My questions is Why, when reading a file .txt , do you duplicate the lines contained in my .txt? That is, if I have a String variable which I read, for example . Juan, Pedro, so-and-so. If I show on screen what is loaded in that variable, it prints me:

Exit:

Juan
Pedro
Fulano
Juan
Pedro
Fulano

I have tried different ways to read a file and I always get the same result (duplicates).

Methods that I have tested with their respective outputs

public void leer() {
        try {
            String ruta = "direccion";
            BufferedReader bf = new BufferedReader(new FileReader(ruta));
            String Cadena = "";
            while ((Cadena = bf.readLine()) != null) {
                System.out.println(Cadena);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }

Exit:

ALBERTO
JUAN
ALBERTO
JUAN
public void leer() {
        try {
            String ruta = "ruta";
            Path path = Paths.get(ruta, ".txt");
            Charset charset = Charset.forName("UTF-8");
            List<String> arrayTexto = new ArrayList<>();
            arrayTexto = Files.readAllLines(path, charset);
            StringBuilder builder = new StringBuilder();
            for (String line : arrayTexto) {
                builder.append(line);
            }
            System.out.println(builder);
        } catch (Exception e) {
        }
    }

Exit

ALBERTO JUAN
ALBERTO JUAN
public void leer() {
        try {
            String ruta = "ruta";
            Path path = Paths.get(ruta, ".txt");
            Stream<String> stream = Files.lines(path);
            stream.forEach(System.out::println);
        } catch (Exception e) {
        }
    }

Exit

ALBERTO
JUAN
ALBERTO
JUAN

As you will see in any method I get duplicates of the content of my .txt in which we suppose that I only have ALBERTO JUAN inside it. What would be the cause of this problem?

I am using Java 8. I already appreciate your help.

    
asked by Gerardo Ferreyra 05.09.2017 в 21:13
source

1 answer

0

The function as you describe it is correct, the most probable is that the error is in how you invoke it. Check that the code that invokes this function is not inside a loop or in any case publish it to help you.

To try you could run:

public static void main(String args[]){
    leer();
}

I should paint without repeating.

    
answered by 05.09.2017 / 21:43
source