簡體   English   中英

java 從文件中刪除文本

[英]java delete text from a file

我創建了一種從文件中刪除文本的方法。 但這不是最好的解決方案。 你能幫我改進一下嗎

它的工作原理如下:

1.使用方法buscarIndiceLibro找到要刪除的文本的position 2.調用方法listarLibros加載孔文件的內容。 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;
    }

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

也嘗試使用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**

謝謝您的幫助

您可以使用 Java.File 之類的庫來執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM