Package br.com.neto.main

Source Code of br.com.neto.main.SerializaEDeserializa

package br.com.neto.main;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import br.com.neto.model.Album;
import br.com.neto.util.Constantes;

/**
* Serializa, deserializa, escreve arquivo txt, l� arquivo e exibe no console.
*
* @author NETO
*
*/
public class SerializaEDeserializa {
 
  private static Constantes c = Constantes.getInstance();

  @SuppressWarnings("static-access")
  public static void main(String[] args) throws IOException,
      ClassNotFoundException {
   
    File diretorio = new File(c.FILE_DIRETORIO);

    if (!diretorio.exists()) {
      diretorio.mkdirs();
    }

    Album albumSerializado = new Album("Pink Floyd", "Animals");
    Album albumSerializado2 = new Album("Pink Floyd", "The Wall");
    Album albumSerializado3 = new Album("Pink Floyd", "The Division Bell");

    //Serializando os objetos
    FileOutputStream fileOutputStream = new FileOutputStream(new File(c.FILE_DIRETORIO + c.SLASH + "album.ser"));
    ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutputStream);
    objectOutput.writeObject(albumSerializado);
    objectOutput.writeObject(albumSerializado2);
    objectOutput.writeObject(albumSerializado3);
    objectOutput.close();

    //Deserializando os objetos
    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(c.FILE_DIRETORIO + c.SLASH + "album.ser")));
    List<Album> albuns = new ArrayList<Album>();
    while (true) {
      try{
        albuns.add((Album) objectInputStream.readObject())
      }catch(EOFException eof){
        break;
      }
    }
    objectInputStream.close();

    // Escrevendo em um txt
    FileWriter fileWriter = new FileWriter(new File(c.FILE_DIRETORIO + c.SLASH + "album.txt"));
    for (Album a : albuns) {
      fileWriter.write(a.getArtista() + " - " + a.getNome() + "\n");
    }
    fileWriter.close();
   
    //Lendo e exibindo no console
    FileReader fileReader = new FileReader(new File(c.FILE_DIRETORIO + c.SLASH + "album.txt"));
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
      System.out.println(line);
    }
    bufferedReader.close();
  }
}
TOP

Related Classes of br.com.neto.main.SerializaEDeserializa

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.