I have to access a file created by me and display its data. The code I have made is as follows: Can someone give me a clue where to go next? I have created the input and output streams and the ArrayList but I don't know how to continue.
public static void main(String[] args) throws FileNotFoundException,
IOException {
int opcion,edad;
String nombre;
Scanner entrada=new Scanner(System.in);
System.out.println("seleccione opcion");
System.out.println("1: Escribir nombre y edad de una persona");
System.out.println("2: Leer y mostrar los datos");
opcion=entrada.nextInt();
if (opcion==1){
System.out.println("Escriba el nombre");
nombre=entrada.next();
System.out.println("Escriba edad");
edad=entrada.nextInt();
System.out.println("Datos guardados correctamente");
}
else if(opcion==2){
System.out.println("Leyendo y mostrando los datos almacenados");
}
else{
System.out.println("opcion no valida");
}
String f = null;
ArrayList<Persona> Personas = new ArrayList<>();
try{
FileOutputStream FileOutputStream = new FileOutputStream(f);
OutputStream fos = null;
ObjectOutputStream ObjectOutputStream = new ObjectOutputStream(fos);}
catch (IOException ex) {
}
try{
FileInputStream fis= new FileInputStream(f);
ObjectInputStream ObjectInputStream = new ObjectInputStream(fis);}
catch (IOException ex) {
}
}
}
As I understand your question, you want to write and read data from a file that contains 'the information' of n 'objects'. For this, and it is important, those objects to be saved must implement the class
Serializable
[ API ]To serialize in Java is very simple and you are on the right track, I leave you some simple methods.
Serialize (Write)
Deserialize (Read) (UPDATED: thanks to Luiggi Mendoza )
If you only wanted to read and write any files here my notes: LINK
You must first create and initialize the List (
ArrayList
), request the data in a loop and store it in the list, to add (put, put, add) the method is used andadd(Object)
toArrayList
obtain the methodget(int)
. Here is an example to guide you: