简体   繁体   English

java 从文件中删除文本

[英]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. 1.使用方法buscarIndiceLibro找到要删除的文本的position 2.调用方法listarLibros加载孔文件的内容。 3.remove from the array the text using the position 4. write again in the file. 3. 使用 position 从数组中删除文本 4. 在文件中再次写入。 /////////////////////// /////////////////////

@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也尝试使用replaceall但没有成功

 **// 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.您可以使用 Java.File 之类的库来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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