How to correctly read a file ignoring certain words in Java?

1

How can I read this .txt file, ignoring the words:

  • Id book:
  • Title:
  • Editorial:
  • List of authors:

    and ignore the entire line:

    • "------- Text:".

Reference image:

I used this code to read the author's code and it works very well:

//Metodo para leer el archivo de autores
public void leerArchivoAutores() throws  IOException{
    FileReader reader = new FileReader(ArchivoAutores);//ArchivoAutores es de tipo File ya definido
    BufferedReader bufReader = new BufferedReader(reader);
    String linea = "";        
    while ((linea= bufReader.readLine())!=null) {
        String[] datosAutores = linea.split("--");
        //En la clase Globales es donde tengo el Arraylist de listaAutores
        Globales.listaAutores.add(new Autor(Integer.parseInt(datosAutores[0]), datosAutores[1], datosAutores[2]));            
    }
}

The question would be   How can I modify this method to read a file like the one in the first image?

    
asked by Reyes_98 24.03.2018 в 02:05
source

4 answers

1

Greetings, Reyes_98.

What you can do is create a method where you read your file and pass in an array those text strings that should be ignored, in this way, when reading your file if any reference to that text is found, it is omitted .

For example:

/**
 * Este método te permite leer cualquier archivo y omitir las palabras
 * ingresadas en el arreglo
 *
 * @param file el archivo que será leído
 * @param textos_a_ignorar el arreglo de textos que se ignorarán
 * @throws FileNotFoundException en caso de que el archivo no se encuentre
 * @throws IOException si ocurre una excepción mientras se leía el archivo
 */
public void leerArchivo(File file, String[] textos_a_ignorar) throws FileNotFoundException, IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);

    String line;
    while ((line = br.readLine()) != null) { // Se lee la siguiente línea del archivo
        for (String texto : textos_a_ignorar) { // recorremos el arreglo de textos que deben ser omitos
            if (line.contains(texto)) { // si se encuentra alguna coincidencia
                line = line.replace(texto, ""); // se reemplaza por un espacio en blanco
            }
        }

        if (!line.isEmpty()) { // después de realizar la búsqueda, si la línea no está en blanco
            System.out.println(line); // se imprime la línea
        }
    }

    // no olvides cerrar
    br.close();
    fr.close();
}

This way, when you call your file, we would do this:

public static void main(String[] args) {
    try {

        // Se crea un arreglo de cadenas de texto con las palabras que deben ser omitidas
        String[] textos_a_ignorar = new String[]{"Id libro:", "Titulo:", "Editorial:", "Lista de autores:", "-------Texto:"};

        // Se llama el método de la clase Main, se envía el archivo y el arreglo
        new Main().leerLibro(new File("Cien años de soledad.txt"), textos_a_ignorar);

    } catch (FileNotFoundException e) { // si el archivo no se encuentra
        System.out.println("El libro no existe");
    } catch (IOException e) { // si ocurre un error leyendo el archivo
        System.out.println("Ocurrió un error leyendo el archivo: " + e);
    }
}

The previous code is just an example, you could change the access of the leerArchivo method to static, so that you do not have to create the instance of Main (in my case this is called my class).

And in the previous way, you would simply have to enter in an arrangement the words and texts that should be omitted from the file you read.

On the other hand, if all you think about reading are those books, you could create a specific method for the books, in your case, let's look at the book that you present to us:

Id libro:7
Titulo:Cien años de soledad
Editorial:Harper, Jonathan Cape
Lista de autores:
Gabriel García Márquez--Colombia
-------Texto:
Muchos años despues, frente al pelotón de fusilamiento, el coronel Aureliano Buendía había de recordar aquella tarde remota en que su padre lo llevó a conocer el hielo. Macondo era entonces una aldea deveinte casas de barro y cañabrava construidas a la orilla de un río de...

If all the books you plan to add or manipulate in your program have the same structure and definition (all have a id , a titulo , a editorial , a lista de autores and the texto of the book), that would serve as a pattern to create a class Libro and therefore, we would also know which words to omit from the files we read, for example:

public class Libro {

    private String id;
    private String titulo;
    private String editorial; // Editorial debería ser otra clase más, esto es un ejemplo
    private String autor; // Autor debería ser otra clase más, esto es un ejemplo
    private String texto;

    // Constructores, getters y setters...
}

And so, we could define a specific method for books:

/**
 * Este método te permite leer un archivo libro
 *
 * @param file el archivo con la información libro
 * @return retorna un arreglo con los datos importantes del libro
 * @throws FileNotFoundException si el archivo no se encuentra
 * @throws IOException si ocurre una excepción leyendo el archivo
 */
public String[] leerLibro(File file) throws FileNotFoundException, IOException {
    // este arreglo nos permitirá almacenar la información de la clase Libro para utilizarla después
    // se define con 5 espacios por nuestras variables que son 5 (id, titulo, editorial, autor y texto)
    String[] datos = new String[5];

    // es el mismo arreglo de antes, pero no hace falta definirlo en el método debido al patrón que mencionamos
    String[] textos_a_ignorar = new String[]{"Id libro:", "Titulo:", "Editorial:", "Lista de autores:", "-------Texto:"};

    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);

    String line;
    int aux = 0; // el auxiliar nos permite recorrer los campos del arreglo datos para almacenar las líneas
    while ((line = br.readLine()) != null) {
        for (String texto : textos_a_ignorar) {
            if (line.contains(texto)) {
                line = line.replace(texto, "");
            }
        }

        if (!line.isEmpty()) {
            datos[aux++] = line; // almacenamos la linea en el arreglo
        }
    }

    // no olvides cerrar
    br.close();
    fr.close();


    /*
    También podríamos retornar la clase libro y no solo los datos:
    Para esto, deberías cambiar el tipo de dato que retorna este método
    (String[]) por Libro

    Libro libro = new Libro();
    libro.setID(datos[0]);
    libro.setTitulo(datos[1]);
    libro.setEditorial(datos[2]);
    libro.setAutor(datos[3]);
    libro.setTexto(datos[4]);

    return libro;
    */

    return datos;
}
    
answered by 24.03.2018 / 19:28
source
1

I think the following code does what you want. Notice that what I do with each data collected is to print it with System.out.println(); . What you want to do with this is your choice:

public static void leerDatos() throws IOException {
    FileReader reader = new FileReader(archivoDatos);
    BufferedReader bufReader = new BufferedReader(reader);
    String linea;
    String dato;
    while ((linea = bufReader.readLine()) != null) {
        String[] li = linea.split(":");
        if (linea.contains(":") && l.length > 1) {
            dato = li[1].trim();
            System.out.println(dato);
        } else if (!linea.contains(":")) {
            dato = linea;
            System.out.println(dato);
        }
    }
    bufReader.close();
}
    
answered by 24.03.2018 в 13:14
1

It may be easier to give the file another format if you can. For example you can add a space and a comma at the end of each attribute. It would be like this:

ID Libro: id ,
Titulo: nombre del libro ,
Editorial: nombre de la editorial ,
Autores:  
Autor 1, Autor2 ,
-------Texto:
texto.

Once the file has that format you can put it all together in one String and separate it by "," and then ":" to separate the pairs and add them to a list, for example Map.

public static void main(String[] args) {
    Map<String, String> atributos = leerAtributos("so.txt");

    //puedes acceder a cada entrada por su nombre usando el metodo get()
    System.out.println(atributos.get("Titulo"));
    System.out.println(atributos.get("Editorial"));

    //o poner todos los valores en tu lisa usando el metodo values()
    List<String> tuLista = new ArrayList<>();
    tuLista.addAll(atributos.values());
    System.out.println(tuLista);
}

static Map<String, String> leerAtributos(String rutaDelArchivo){
    Path archivo = Paths.get(rutaDelArchivo);//nombre del archivo a leer
    try{
        //Esto pondra el archivo entero en una sola String
        //y luego se puede usar split para separar los atributos
        String[] parejas = Files.lines(archivo)
                                .reduce(String::concat)
                                .get().split(" ,");

        //Esto separa cada lina y crea un Map con cada pareja 
        Map<String, String> valores = Arrays.stream(parejas)
                                             .map(e -> e.split(":"))
                                             .collect(Collectors.toMap(e -> e[0]  , e -> e[1]));  
        return valores;
    }
    catch(Exception e){
        e.printStackTrace();
    }  
    return null;
}

Passing the file path to the function readAttributes () will return a Map that allows you to access each attribute by the name you have placed to the left of the ':' or all the attributes at the same time if you use the values function ().

to use this code you have to import:

import java.util.*;
import java.util.stream.Collectors;
import java.nio.file.*;
    
answered by 24.03.2018 в 20:08
0

This code could also be used to read that file:

public String[] leerLibro(int indiceLibro) throws FileNotFoundException, IOException {
    // se define con 5 espacios por nuestras variables que son 5 (id, titulo, editorial, autor ,texto)
    String[] datosDelLibro = new String[5];

    //Texto que vamos a ignorar del arreglo
    String[] texto_A_Ignorar = new String[]{"Id libro:", "Titulo:", "Editorial:", "Lista de autores:", "-------Texto:"};       

    FileReader reader = new FileReader(ArchivosDeLibros.get(indiceLibro));
    BufferedReader bufferedReader = new BufferedReader(reader);

    String line;
    int numDeLinea=1; //contador de lineas recorridas 
    while ((line = bufferedReader.readLine()) != null) {            
        if (numDeLinea==1) {//Id:
            if (!line.isEmpty()) {
                line = line.replace(texto_A_Ignorar[0], "");
                datosDelLibro[0] = line;                    
            }
        }
        if (numDeLinea==2) {//Título:
            if (!line.isEmpty()) {
                line = line.replace(texto_A_Ignorar[1], "");
                datosDelLibro[1] = line;                    
            }
        }
        if (numDeLinea==3) {//Editorial:
            if (!line.isEmpty()) {
                line = line.replace(texto_A_Ignorar[2], "");
                datosDelLibro[2] = line;                    
            }
        }
        if (numDeLinea==4) {//Lista de Autores:
            if (!line.isEmpty()) {
                line = line.replace(texto_A_Ignorar[3], "");
                datosDelLibro[3] = line;                    
            }
        }
        if (numDeLinea>5) {//Texto del libro
            if (!line.isEmpty()) {                    
                datosDelLibro[4] += line;
            }
        }
        numDeLinea++;//cambio de linea
    }//fin for


    bufferedReader.close();
    reader.close();       


    return  datosDelLibro;//(id, titulo, editorial, autor ,texto)
}

That if you leave all the authors in a single line

Id libro:1
Titulo:Cien años de soledad
Editorial:Harper, Jonathan Cape
Lista de autores:Gabriel García Márquez--Colombia,
-------Texto: 
Muchos años después, frente al pelotón de fusilamiento, el coronel Aureliano 
Buendía había de recordar aquella tarde remota en que su padre lo llevó a 
conocer el hielo”. Con estas palabras empieza una novela ya legendaria en 
los anales de la literatura universal, una de las aventuras literarias más 
fascinantes del ...

Although without problem I think that to read the authors you can use the .split (",") method

    
answered by 25.03.2018 в 03:23