Delete Row according to text in a Java Txt

2

Good I have a code like this:

String ruta = "archivo.txt";
File archivo = new File(ruta);
String texto;
String[] a;
String pre= "texto a encontrar";
  FileReader f = new FileReader(archivo);
  FileWriter f1 = new FileWriter(archivo);
  BufferedReader b = new BufferedReader(f);
  PrintWriter out = new PrintWriter(new BufferedWriter(f1));
 while((texto = b.readLine())!=null) {
 a = texto.split("==");
       String h = a[0];    



       if (h.equals(pre)){
          out.println("");

           f1.close();
       }        

What I want to get to do is, according to a text, be able to eliminate that row without having to delete or overwrite the entire file just the row where that text appears. Thanks and best regards

    
asked by zekamodz 11.05.2018 в 13:28
source

1 answer

4

An easy way to modify the entire file by removing all the rows that do not contain a certain string:

public void eliminarFilas(String rutaAlFichero, String cadena) throws IOException{
    Path path = Paths.get(rutaAlFichero);
    List<String> lineas = Files.readAllLines(path);
    lineas = lineas.stream()
                    .filter(linea->!linea.contains(cadena))
                    .collect(Collectors.toList());
    Files.write(path, lineas);
}
    
answered by 11.05.2018 / 14:04
source