Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package archivos2;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.EOFException;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.NotSerializableException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.util.ArrayList;
- public class Main
- {
- private static File f = new File("datos.bin");
- public static void main(String[] args) {
- try
- {
- if (!f.exists())
- {
- System.out.println("No existe");
- escribirNuevo();
- }
- else
- {
- System.out.println("Existe");
- escribirAgregar();
- }
- leer();
- }
- catch (EOFException e) {
- System.out.println("FIN del Archivo");
- }
- catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (NotSerializableException e) {
- e.printStackTrace();
- }
- catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static void leer() throws IOException, ClassNotFoundException
- {
- if (f.exists())
- {
- FileInputStream fileInputStream = new FileInputStream(f);
- ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
- int lectura = 1;
- while (lectura == 1 )
- {
- Persona aux = (Persona)inputStream.readObject();
- System.out.println(aux.getNombre());
- }
- inputStream.close();
- }
- }
- public static void escribirNuevo() throws Exception
- {
- FileOutputStream fileOutputStream = new FileOutputStream(f);
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
- objectOutputStream.writeObject(getPersona("gonzalo"));
- fileOutputStream.close();
- objectOutputStream.close();
- }
- public static void escribirAgregar() throws Exception
- {
- FileOutputStream fileOutputStream = new FileOutputStream("datos.bin",true);
- MyObjectOutputStream myObjectOutputStream = new MyObjectOutputStream(fileOutputStream);
- myObjectOutputStream.writeObject(getPersona("juan"));
- fileOutputStream.close();
- myObjectOutputStream.close();
- }
- public static Persona getPersona(String nombre)
- {
- Persona p = new Persona();
- p.setNombre(nombre);
- return p;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement