Otra alternativa (con streams) seria usar HashSet, ya que no permite duplicados.
Main:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
String fileName = "pathtofile.txt";
Set<String> list = new HashSet<String>();
Path path = Paths.get(fileName);
try (Stream<String> lines = Files.lines(path)) {
list = lines
.collect(Collectors.toSet());
} catch (IOException ex) {
//capturar la excepción
}
//imprimir en consola
list.forEach(e -> System.out.println(e));
//Reemplazar archivo
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
Iterator<String> it = list.iterator();
while(it.hasNext()) {
out.write(it.next());
out.newLine();
}
out.close();
}
}
Finalmente este seria el archivo txt reemplazado:
1323
3455
7445
5345