whiplk

Salvar.java

Feb 5th, 2014
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.FileWriter;
  7. import java.io.IOException;
  8.  
  9. public class Salvar {
  10.     private static final String file = "db.txt";
  11.    
  12.     public void escrever(List<Pessoa> pessoas) {
  13.         File f = new File(file);
  14.         FileWriter fw = null;
  15.         BufferedWriter bw = null;
  16.        
  17.         try {
  18.             fw = new FileWriter(f);
  19.             bw = new BufferedWriter(fw);
  20.            
  21.             for (Pessoa i : pessoas) {
  22.                 bw.write(i.getCpf() + "," + i.getNome() + "," + i.getData());
  23.                 bw.newLine();
  24.             }          
  25.         } catch(IOException e) {
  26.             System.err.print("Erro no acesso do arquivo.");
  27.         }
  28.         finally {
  29.             try {
  30.                 fw.close();
  31.                 bw.close();
  32.             } catch (IOException e) {
  33.                
  34.             }
  35.         }
  36.     }
  37.    
  38.     public List<Pessoa> ler() {
  39.         File f = new File(file);
  40.         FileReader fr = null;
  41.         BufferedReader br = null;
  42.    
  43.         List<Pessoa> pessoas = new ArrayList<Pessoa>();
  44.        
  45.         try {
  46.             fr = new FileReader(f);
  47.             br = new BufferedReader(fr);
  48.            
  49.             String[] dados;
  50.            
  51.             for (String i = br.readLine(); i != null; i = br.readLine()) {
  52.                
  53.                 dados = i.split(",");
  54.                
  55.                 Pessoa temp = new Pessoa(Long.parseLong(dados[0]), dados[1], dados[2]);
  56.                 pessoas.add(temp);
  57.             }
  58.             return pessoas;
  59.         } catch(IOException e) {
  60.             System.err.print("Erro no acesso do arquivo.");
  61.         }
  62.         finally {
  63.             try {
  64.                 fr.close();
  65.                 br.close();
  66.             } catch (IOException e) {
  67.                
  68.             }
  69.         }
  70.        
  71.         return pessoas;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment