简体   繁体   中英

java delete text from a file

i created a method that removes text from a file. but it is not the best solution. can you please help me improve it

it work as follow:

1.use the method buscarIndiceLibro to find the position of the text to delete 2.call the method listarLibros to load the content of the hole file. 3.remove from the array the text using the position 4. write again in the file. ///////////////////////

@Override
    public void borrarLibroDeArchivo(String nombrelibroBorrar, String nombreRecurso) throws ErrorEscrituraDatos {
               
try {
            
            int posicion =  this.buscarIndiceLibro(nombrelibroBorrar, nombreRecurso);
            System.out.println("posicion"+ posicion+"\n");
            var catalogocompleto=   this.listarLibros(nombreRecurso);
            System.out.println("catalogo completo"+ catalogocompleto+"\n");
            catalogocompleto.remove(posicion);
           
        
            try {
                PrintWriter sobreEscribir = new PrintWriter(new FileWriter(nombreRecurso));
                
                for( libro posicionArray: catalogocompleto){
                
                    libro agregarArchivo =posicionArray;
                
                sobreEscribir.println(agregarArchivo.toString());
                }
                
                
                
                
                
                
                
                sobreEscribir.close();
                
                // System.out.println("el nuevo catalogo de libros es: "+ this.listarLibros(nombreRecurso));
            } catch (IOException ex) {
                ex.printStackTrace(System.out);
                System.out.println(" error al escribir el archivo");
            }
            
            
        } catch (ErrorLeyendoDatos ex) {
            ex.printStackTrace(System.out);
        }



    }

//////////////

@Override
    public List<libro> listarLibros(String nombreRecurso) throws ErrorLeyendoDatos {
        var archivo = new File(nombreRecurso);
        List<libro> catalogoLibros = new ArrayList<>();
        try {
            //cargar el contenido del archivo en memoria
            BufferedReader datosEntrada = new BufferedReader(new FileReader(archivo));
            // creo una variable para leer cada linea
            String leerLinea = null;
            leerLinea = datosEntrada.readLine();
            while (leerLinea != null) {
                // se crea un objeto tipo libro para meter al array
                libro nombreLibro = new libro(leerLinea);
                catalogoLibros.add(nombreLibro);
                leerLinea = datosEntrada.readLine();
            }
            datosEntrada.close();
        } catch (FileNotFoundException ex) {
            // atrapa el error al leer el archivo
            ex.printStackTrace(System.out);
            throw new ErrorLeyendoDatos("error al listar las peliculas" + ex.getMessage());
        } catch (IOException ex) {
            // atrapa el erro al leer la linea
            ex.printStackTrace();
            throw new ErrorLeyendoDatos("error al leer la Pelicula" + ex.getMessage());
        }
        return catalogoLibros;
    }

////////////////////////////////

public int buscarIndiceLibro(String nombreLibroBuscar, String nombreRecurso) throws ErrorLeyendoDatos {
        var archivo = new File(nombreRecurso);
        int posicion = 0;
        try {
            var datosEntrada = new BufferedReader(new FileReader(archivo));
            var leerlinea = datosEntrada.readLine();
            int index = 0;
            while (leerlinea != null) {
                if (nombreLibroBuscar != null && nombreLibroBuscar.equalsIgnoreCase(leerlinea)) {
                    posicion = index;
                    break;
                }
                leerlinea = datosEntrada.readLine();
                index++;
            }
            datosEntrada.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            throw new ErrorLeyendoDatos("error leyendo el archivo" + ex.getMessage());
        } catch (IOException ex) {
            ex.printStackTrace(System.out);
            throw new ErrorLeyendoDatos("error leyendo el archivo" + ex.getMessage());
        }
        return posicion;
    }

///////////////////////////////**

also tried to use replaceall without success

 **// metodo no funciono
//
//        try {
//            
//            
//            
//            
//            BufferedReader leerarchivo = new BufferedReader(new FileReader(archivo));
//            String archivoCompleto = leerarchivo.toString();
//            System.out.println("El contenido completo del archivo es " + archivoCompleto);
//          ///borrar la pelicula
//            var archivoEditado = archivoCompleto.replaceAll(nombrelibroBorrar, "");
//            //volver a escribir el archivo
//            PrintWriter sobreescribir = new PrintWriter(new FileWriter(nombreRecurso));
//            sobreescribir.append(archivoEditado);
//             sobreescribir.close();
//
//            leerarchivo.close();
//           
//
//        } catch (IOException ex) {
//            ex.printStackTrace(System.out);
//            throw new ErrorEscrituraDatos("error al eliminar la pelicula" + ex.getMessage());
//        }

// fin metodo no funciono**

Thank you for your assistance

You can use libraries like Java.File for doing this operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM