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.