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;
}