Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- /______________________________Exemplo de Classe IDAO Generica______________________________
- */
- package br.com.exemplo.interfaces;
- import java.io.IOException;
- import java.util.Set;
- public interface IDao<T> {
- void escreverArquivo(Set<T> clientes) throws IOException;
- Set<T> lerArquivo() throws IOException, ClassNotFoundException;
- }
- /*
- /______________________________Exemplo de Classe DAO Generica______________________________
- */
- package br.com.exemplo.model;
- import br.com.exemplo.interfaces.IDao;
- import br.com.exemplo.util.Util;
- import java.io.*;
- import java.util.HashSet;
- import java.util.Set;
- public class Dao<T> implements IDao<T> {
- private File arquivo;
- private Class classe;
- public Dao(Class classe) {
- this.arquivo = new File(classe.getSimpleName() + ".data");
- this.classe = classe;
- }
- public void escreverArquivo(Set<T> clientes) throws IOException {
- FileOutputStream fos = new FileOutputStream(arquivo);
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(clientes);
- oos.flush();
- oos.close();
- fos.close();
- }
- public Set<T> lerArquivo() throws IOException, ClassNotFoundException {
- Set<T> clientes = null;
- if (!arquivo.exists()) {
- arquivo.createNewFile();
- }
- //Tratamento do erro EOFException
- if (Util.isFileEmpty(arquivo)) {
- clientes = new HashSet<>();
- return clientes;
- }
- FileInputStream fis = new FileInputStream(arquivo);
- ObjectInputStream ois = new ObjectInputStream(fis);
- clientes = (HashSet<T>) ois.readObject();
- ois.close();
- fis.close();
- return clientes;
- }
- }
Add Comment
Please, Sign In to add comment