Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 7, 2022 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/335caac3c3816612e4ba3f6cbb3867f4 to your computer and use it in GitHub Desktop.
Save parzibyte/335caac3c3816612e4ba3f6cbb3867f4 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
class Persona {
private String nombre, direccion;
private int edad;
public Persona(String nombre, int edad, String direccion) {
this.nombre = nombre;
this.edad = edad;
this.direccion = direccion;
}
@Override
public String toString() {
return "Nombre: " + this.nombre + " edad: " + this.edad + ", direccion: " + this.direccion;
}
public String getNombre() {
return this.nombre;
}
public String getDireccion() {
return this.direccion;
}
public int getEdad() {
return this.edad;
}
}
class Main {
public static ArrayList<Persona> obtener() {
final String NOMBRE_ARCHIVO = "personas.txt";
final String SEPARADOR_CAMPO = ";";
ArrayList<Persona> personas = new ArrayList<>();
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader(NOMBRE_ARCHIVO);
bufferedReader = new BufferedReader(fileReader);
String linea;
while ((linea = bufferedReader.readLine()) != null) {
String[] personaComoArreglo = linea.split(SEPARADOR_CAMPO);
personas.add(new Persona(personaComoArreglo[0], Integer.valueOf(personaComoArreglo[1]),
personaComoArreglo[2]));
}
} catch (IOException e) {
System.out.println("Excepción leyendo archivo: " + e.getMessage());
} finally {
try {
if (fileReader != null) {
fileReader.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
System.out.println("Excepción cerrando: " + e.getMessage());
}
return personas;
}
}
public static void main(String[] args) {
ArrayList<Persona> personas = obtener();
// Podemos imprimirlas...
System.out.println(personas);
// O recorrerlas
for (int x = 0; x < personas.size(); x++) {
Persona persona = personas.get(x);
System.out.println("Tenemos una persona con nombre " + persona.getNombre() + " edad " + persona.getEdad()
+ " y direccion " + persona.getDireccion());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment