-
-
Save parzibyte/335caac3c3816612e4ba3f6cbb3867f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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