Kabbalah

Exemplo DAO Generico - Java

Dec 2nd, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. /*
  2. /______________________________Exemplo de Classe IDAO Generica______________________________
  3. */
  4. package br.com.exemplo.interfaces;
  5.  
  6. import java.io.IOException;
  7. import java.util.Set;
  8.  
  9. public interface IDao<T> {
  10.     void escreverArquivo(Set<T> clientes) throws IOException;
  11.  
  12.     Set<T> lerArquivo() throws IOException, ClassNotFoundException;
  13. }
  14.  
  15. /*
  16. /______________________________Exemplo de Classe DAO Generica______________________________
  17. */
  18. package br.com.exemplo.model;
  19.  
  20. import br.com.exemplo.interfaces.IDao;
  21. import br.com.exemplo.util.Util;
  22.  
  23. import java.io.*;
  24. import java.util.HashSet;
  25. import java.util.Set;
  26.  
  27. public class Dao<T> implements IDao<T> {
  28.     private File arquivo;
  29.     private Class classe;
  30.  
  31.     public Dao(Class classe) {
  32.         this.arquivo = new File(classe.getSimpleName() + ".data");
  33.         this.classe = classe;
  34.     }
  35.  
  36.     public void escreverArquivo(Set<T> clientes) throws IOException {
  37.         FileOutputStream fos = new FileOutputStream(arquivo);
  38.         ObjectOutputStream oos = new ObjectOutputStream(fos);
  39.  
  40.         oos.writeObject(clientes);
  41.  
  42.         oos.flush();
  43.         oos.close();
  44.         fos.close();
  45.     }
  46.  
  47.     public Set<T> lerArquivo() throws IOException, ClassNotFoundException {
  48.         Set<T> clientes = null;
  49.  
  50.         if (!arquivo.exists()) {
  51.             arquivo.createNewFile();
  52.         }
  53.  
  54.         //Tratamento do erro EOFException
  55.         if (Util.isFileEmpty(arquivo)) {
  56.             clientes = new HashSet<>();
  57.             return clientes;
  58.         }
  59.  
  60.  
  61.         FileInputStream fis = new FileInputStream(arquivo);
  62.         ObjectInputStream ois = new ObjectInputStream(fis);
  63.  
  64.         clientes = (HashSet<T>) ois.readObject();
  65.  
  66.         ois.close();
  67.         fis.close();
  68.  
  69.         return clientes;
  70.     }
  71. }
Add Comment
Please, Sign In to add comment