GClients.java


package gclients;

import java.io.*;




public class GClients {
   RandomAccessFile fc;
   
   
    GClients(){
    try{   // Ouverture du fichier clients.dat en mode
           //Lecture écriture
        
        fc =new RandomAccessFile("c:/clients.dat","rw");
       
    }
catch(IOException e){
    
    System.out.print("Erreur d'ouverture de fichier:" + e.getMessage());
}}
    
    
    
    
    public static void main(String[] args) {
        GClients gc = new GClients();
        
        
        // Affichage du menu principal de l'application
        int choix;
        do {
            System.out.println("1- Ajouter Un client");
            System.out.println("2- Afficher tous les clients");
            System.out.println("3- Quitter");
            choix=Integer.parseInt(Util.lireLigne());
       
        switch(choix){
            case 1: 
                gc.ajouter();
                break;
            case 2:
                gc.afficherClients();
                break;
              
            
        }
         }while(choix!=3);
        
        
        
        
        // Fermeture du fichier
        try {
          gc.fc.close();
        } catch (IOException ex) {
            
        }
        
        
        
        
    }

    
    //Affiche tous les clients
    private void afficherClients() {
        try {
            fc.seek(0);
            //Taille du fichier en octets
            long taille=fc.length();
            long position=0;
            
            while(position<taille){
                afficher();
                position=fc.getFilePointer();
            }
            
        } catch (IOException ex) {
           
        }
       
    }
    
// Ajoute un nouveau client dans le fichier clients.dat
    private void ajouter(){
        try {
            Client cl = new Client();
            fc.seek(fc.length());
            fc.writeUTF(cl.getNom());
            fc.writeUTF(cl.getPrenom());
            fc.writeUTF(cl.getAdresseLivraison());
            fc.writeInt(cl.getAge());
            fc.writeInt(cl.getNombreCommandes());
            fc.writeBoolean(cl.getMarie());
            
            
        } catch (IOException ex) {
          System.out.print("Erreur d'ajout de données:"+ ex.getMessage());
        }


}

 
private void afficher(){
            try {
            
          String nom=fc.readUTF();
          String prenom=fc.readUTF();
          String adresse=fc.readUTF();
            int age =fc.readInt();
            int nc=fc.readInt();
            boolean m=fc.readBoolean();
            Client cl=new Client(nom,prenom,age,m,adresse,nc);
            System.out.println(cl);
            
        } catch (IOException ex) {
          System.out.print("Erreur d'accès au fichier:"+ ex.getMessage());
        }
}
}