Bonjour,

En fait, je viens du monde Delphi et je me mets à Java sous windows. Pour résumer, je fais une appli en swing (sans base de donnée) et j'ai besoin de stocker des éléments dans un fichier d'initialisation.
Donc, j'ai essayé de refaire un fichier.ini identique à ce que l'on trouve en Delphi.
C'est un fichier texte où sont les données initiales du programme. Lire/ecrire dans un fichier texte en Java, c'est possible.
Voici la structure fichier dans lequel il faut pouvoir lire et écrire :

[FRUITS]
UN=3
DEUX=4
[POSITION]
POINT1=G,3,4
POINT2=N,5,7

Un truc simple en Delphi : le fichier.ini par exemple POSITION indique ce dont il s'agit et POINT1= Couleur,abscisse,ordonnée pareil pour les autres à afficher au lancement du programme.
J'ai regardé la faq et trouvé le moyen de lire / écrire dans un fichier avec Java.
Donc après moultes essais d'utilisation de l'itérator des Arraylist<String> en Java, j'ai vu que ce n'était pas adapté.

Explication : On ne peut pas remettre les Iterator au début (J'ai regardé partout) et le programme devient ingérable si on lit et écrit plusiers fois avec le même objet.
Etape1 : je veux lire une valeur : ok, l'itérator atteint celle-ci et la renvoie.
Etape2 : je veux lire une seconde valeur qui se trouve avant la premiere : l'itérator étant après cette valeur, il continue à itérer jusqu'à la fin du fichier et ne trouve rien ...

J'ai donc retiré les Itérators et je parcours simplement les listes avec des boucles, et là ça marche. Bon, mais c'est du code de débutant.

Je n'ai pas trouvé l'équivalent de l'inifile en Java. Peut-être que je ré-invente la roue alors qu'une classe Java lisant les fichiers d'initialisation existe(?)
Je pense aussi aux HashMaps, mais j'ai pas encore essayé.

Donc voici le code et si quelqu'un a une idée/critique constructive/conseil.
Si j'ai la chance de tomber sur quelqu'un connaissant Delphi et Java Merci d'avance.

Vadim

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
 
package code;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 *
 * @author Vadim
 */
public class Inifile {
 
    private boolean modifie=false;
    private String lu;
    private String nomfichier; 
    private List<String> items;//Contenu d'une section
    private List<String> contenufichier;
    private List<String> fichiervide;
    private PrintWriter sortie=null;
 
    public Inifile(String nomfichier) throws IOException {
        lu="";
 
        this.nomfichier = nomfichier;//MEF! ça efface tout!
        if (!fileexists(nomfichier)){
            sortie = new PrintWriter(nomfichier);
            sortie.flush();
            sortie.close();
            sortie=null;
        }
        getContenuFichier(nomfichier);
    }
 
    public boolean sauve() {
       if (modifie==false) return true;
       try {
        sortie = new PrintWriter(nomfichier);
       for (int i=0;i<contenufichier.size();i++) {
          sortie.println(contenufichier.get(i));
      }
            sortie.flush();
            sortie.close();
            sortie=null;}
        catch (Exception ex ){
            return false;
        }
        return true;
    }
 
 
    public boolean fileexists(String NomFichier){
        File f = new File(NomFichier);
        return f.exists() && !f.isDirectory();
    }
 
 
    private List<String> getContenuFichier(String NomFichier) throws IOException {
        contenufichier=null;
        contenufichier=new ArrayList<>();
        try {
            BufferedReader entree = new BufferedReader(new FileReader(nomfichier));
            String line = entree.readLine();
           // contenufichier.add(line);
            while (line != null){
                 contenufichier.add(line);
                 line = entree.readLine();                
             }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Inifile.class.getName()).log(Level.SEVERE, null, ex);
        }
       modifie=false;
       return contenufichier;
   }
 
   //Ecrire dans un fichier d'un autre nom
    public void ecrireFichier(String nomfichier) throws FileNotFoundException{
      sortie = new PrintWriter(nomfichier);
 
      for (int i=0;i<contenufichier.size();i++) {
          sortie.println(contenufichier.get(i));
      }
      sortie.flush();
      sortie.close();
      sortie=null;
    } 
 
 
   public String renommerSection(String ancienNom,String NouveauNom){
     int p=trouvesection("["+ancienNom.toUpperCase().trim()+"]");
     if (NouveauNom.trim()=="") return "Section vide";
     if (p==-1) return "Section inconnue";
     contenufichier.set(p, "["+NouveauNom.toUpperCase().trim()+"]");
     return "ok";  
   }
 
 
    public List<String> lireSection(String NomSection) throws FileNotFoundException {
        lu = "";
        int psect=this.trouvesection(NomSection);  
        if (psect==-1) return null;
        if (items == null) {
            items = new ArrayList<>();
        }
        items.clear();
        for (int i=psect+1;i<contenufichier.size();i++) {
        lu=contenufichier.get(i);
        if (lu.trim().startsWith("[")) {
        return items;} //on sort
        items.add(lu);
        }
       return items;
    }
 
   //Renvoie les valeurs sans l'identifiant (utilisable si séries homogènes 
    public List<String> lireContenuSection(String NomSection) {
    lu = "";
        int psect=this.trouvesection(NomSection);  
        if (psect==-1) return null;
        if (items == null) {
            items = new ArrayList<>();
        }
        items.clear();
        for (int i=psect+1;i<contenufichier.size();i++) {
        lu=contenufichier.get(i);
        int p=lu.indexOf("=");
        lu=lu.substring(p+1);
        if (lu.trim().startsWith("[")) {
        return items;} //on sort
        items.add(lu);
        }
       return items;
 
}
 
 
    public String lireValeur(String nomSection, String NomItem,String defaut) throws FileNotFoundException{
     String valeur=defaut;
     int pitem=trouveItem(nomSection,NomItem);
     if (pitem==-1) return defaut;
     valeur=contenufichier.get(pitem);
     int p=valeur.indexOf("=");
     valeur=valeur.substring(p+1);
     return valeur;
   }
 
   public int lireentier(String nomSection, String NomItem,int defaut) throws FileNotFoundException {
      String lu ;
      int val;
        try {
            lu = lireValeur(nomSection,NomItem,Integer.toBinaryString(defaut));
        } catch (NumberFormatException ex) {
            val=defaut;
            return defaut;
        }
 
      try{
      val= Integer.parseInt(lu);}
      catch  (Exception e) {val=defaut;}
      return val; 
   }
 
 
  public float lirefloat(String nomSection, String NomItem,float defaut){
      String lu="" ;
      String strdef;
      float val=0;
      try {
          strdef=String.valueOf(defaut);
      }catch  (Exception e){
       strdef="0";  
       defaut=0;
      }
      try {
         lu = lireValeur(nomSection,NomItem,strdef);
      }catch  (Exception e){
         val=defaut;    
      }
 
      val=Float.valueOf(lu.replace(',','.')).floatValue();
 
     return val; 
  }
 
 
////////////////////////////////////////////////////////////////////////////////
////////////////////// Ecriture dans un fichier ini ////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//TODO : Manque les expressions régulières pourv tolérer les espaces entre crochets et signe=    
 
    public String normalise(String chaine){
        chaine=chaine.replace(String.valueOf((char) 160), "");
        if (chaine.startsWith("[")&&chaine.endsWith("]"))
        { chaine=chaine.toUpperCase().trim();} 
        return chaine;
    }
 
    public String normaliseSection(String chaine){
       chaine=chaine.replace(String.valueOf((char) 160), ""); 
       if (!chaine.startsWith("[")) chaine = "["+chaine;
       if (!chaine.endsWith("]")) chaine = chaine+"]";
       { chaine=chaine.toUpperCase().trim();}
      return chaine;  
    }
 
    public void clear() {
        contenufichier.clear();
    }
   //Attention entre la lecture et l'écriture! 
    public int trouvesection(String nomSection){
     int posSection=-1;   
     nomSection=normaliseSection(nomSection);
     for (int i=0;i<contenufichier.size();i++) {
        posSection=-1;
        lu=contenufichier.get(i);
        lu = normalise(lu);
        if (lu.equals(nomSection)) {//Section concernée
        posSection=i;
        break;
        }}   
        return posSection; 
    }
 
    public int trouveItem(String nomSection,String nomItem){
    int posSection=trouvesection(nomSection);
    int posItem=-1;
    String st="";
    nomItem=normalise(nomItem);
     for (int i=posSection+1;i<contenufichier.size();i++) { 
          st=contenufichier.get(i);
          if (st.startsWith("[")&&st.endsWith("]")) //La section est vide
          {   
              break;
          } //Sort de la boucle  
          else {
          if (st.trim().startsWith(nomItem.toUpperCase())) {//Item trouvé
           posItem=i;   
          } 
        }
      }//for    
      return posItem;  
    }
 
 
    ///m'enfin?
    public String ecrirevaleur(String nomSection, String NomItem, String valeur) throws FileNotFoundException, IOException{
        //Iterator<String> iterator = contenufichier.iterator();//Souci = pas possible de le faire revenir a zéro
        String lu;
        String st="";
        boolean b;
        int num = 0;
        int s=0;
        NomItem=NomItem.trim();
        NomItem=NomItem.replace("[", "");
        NomItem=NomItem.replace("]", "");
        if ((nomSection=="")||(NomItem=="")) return "ERREUR Chaines identifiantes vides";
        nomSection="["+nomSection.toUpperCase().trim()+"]";
 
        int posSection=-1;
        int posItem=-1;
       // 1-On cherche la section
        posSection=trouvesection(nomSection);
        st=normalise(NomItem).toUpperCase()+"="+valeur.trim();
        //Cas 1 : section existe pas
        if (posSection==-1){
            contenufichier.add(nomSection);
            contenufichier.add(st);
        } else {//On cherche l'existence de l'item dans la section
          posItem=trouveItem(nomSection,NomItem) ; 
 
      if (posItem==-1) {
      contenufichier.add(posSection+1,st);}
      else {contenufichier.set(posItem,st);  } 
    }
       modifie=true;
       return st.trim();
    } 
 
 
    public void effacersection(String nomsection) throws FileNotFoundException{
    // Iterator<String> iterator = contenufichier.iterator(); Pas possible a réinitialiser
     int num=trouvesection(nomsection);
     if (num==-1) return;
      modifie=true;
     String st="";
        while (!st.startsWith("[")) {
         contenufichier.remove(num);
         st=contenufichier.get(num);
         if (st==null) return;
       }
      }
 
    public void effacervaleur(String nomSection, String NomItem) throws FileNotFoundException{
       int p=trouveItem(nomSection,NomItem);
       if (p==-1) return;
       contenufichier.remove(p);
       modifie=true;
    }  
 
 
 
 
    //===============================================================================
    //========================= POUR DEBOGUAGE ======================================
    //===============================================================================
 
    //Pour le déboguage
    public void direcontenufichier() {
        System.out.println("Taille : "+contenufichier.size());  
        for (int i=0;i<contenufichier.size();i++) {
        System.out.println(contenufichier.get(i)); 
        }
    }
 
    public void direcontenusection(String nomSection) throws FileNotFoundException{
       lireSection(nomSection);
       for (int i=0;i<items.size();i++) {
        System.out.println(items.get(i)); 
        } 
    }
 
    public void direvaleur(String nomSection,String nomvaleur,String defaut) throws FileNotFoundException {
     String lu;
     lu=lireValeur(nomSection,nomvaleur,defaut); 
     System.out.println(lu);
    }
 
    public void direvaleurint(String nomSection,String nomvaleur,int defaut) throws FileNotFoundException {
     int lu;
     lu=lireentier(nomSection,nomvaleur,defaut); 
     System.out.println(lu);
    }
 
    public void direvaleurfloat(String nomSection,String nomvaleur,float defaut){
     float lu; 
     lu=lirefloat(nomSection,nomvaleur,defaut); 
     System.out.println(lu);
    }
}