IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Entrée/Sortie Java Discussion :

BufferReader et InpuStreamReader ?


Sujet :

Entrée/Sortie Java

  1. #1
    Membre confirmé
    Inscrit en
    Janvier 2007
    Messages
    94
    Détails du profil
    Informations forums :
    Inscription : Janvier 2007
    Messages : 94
    Par défaut BufferReader et InpuStreamReader ?
    Bonjour,

    j'aimerai avoir accès à un fichier .ini en java et j'ai trouvé quelques informations sur internet et notamment 2 classes ProfileReader et INIHandler que j'ai fusionner pour avec toutes les focntionnalités désirées.

    voila ce que j'obtiens :

    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
     
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.HashMap;
    import java.util.Hashtable;
    import java.util.Iterator;
    import java.util.StringTokenizer;
     
    public class ProfileReader {
     
        /**
         * 
         */
        private String configFilename;
        /**
         * 
         */
        private Hashtable sections;
        /**
         * 
         */
        private HashMap sectionMap;
        /**
         * 
         */
        private HashMap newPairMap;
     
        /** 
         * Creates a new ProfileReader 
         */
        public ProfileReader(String inFile) {
            this.sections = new Hashtable();
            this.sectionMap = new HashMap();
            this.newPairMap = new HashMap();
            this.configFilename = inFile;
        }
     
        public void loadSection() {
     
            BufferedReader fs = null;
     
            try {
                String line;
                String section = null;
                HashMap map = null;
                fs = new BufferedReader(new FileReader(this.configFilename));
                while ((line = fs.readLine()) != null) {
                    // check for "[", if not this is a name-value pair
                    if (line.indexOf("[") == -1) {
                        String name;
                        String value;
                        if (line.trim().length() > 0) {
                            line = line.trim();
                            if (line.indexOf("=") > -1) {
                                name = line.substring(0, line.indexOf("=")).trim();
                                value = line.substring(line.indexOf("=") + 1,
                                        line.length()).trim();
                            } else {
                                name = line.trim();
                                value = "";
                            }
                            map.put(name, value);
                        }
                    } else { // this is the section line
                        // a new section begins
                        if (map != null) {
                            if (map.size() != 0) {
                                this.sectionMap.put(section, map);
                            }
                        }
                        line = line.trim();
                        section = line.substring(1, line.length() - 1);
                        map = new HashMap();
                    }
                }
                // add the last map
                if (map.size() != 0) {
                    this.sectionMap.put(section, map);
                }
            } catch (FileNotFoundException f) {
                // take care
            } catch (IOException i) {
                // take care
            } catch (NullPointerException e) {
                // Section was not found
            } finally {
                try {
                    fs.close();
                } catch (Exception e) {
                    // take care
                }
            }
        }
     
        /** 
         * Load the current objet with the data found in the given stream 
         * @param aStream the stream that represent the INI file. 
         * @throws Exception in case of problems. 
         */
        public void load(InputStream aStream) throws Exception {
            if (null == aStream) {
                return;
            }
     
            BufferedReader bReader = new BufferedReader(new InputStreamReader(aStream));
            String line = null;
            String sectionName = null;
            Hashtable section = null;
     
            while ((line = bReader.readLine()) != null) {
                line = line.trim();
                // All the data should be in a section 
                if (null == sectionName) {
                    if ((!line.startsWith("[")) || (!line.endsWith("]"))) {
                        throw new Exception("Invalid format: data found outside section");
                    }
     
                    sectionName = line.substring(1, line.length() - 1).trim();
                    addSection(sectionName);
                    section = getSection(sectionName);
                } else {
                    if (line.startsWith("[")) {
                        if (!line.endsWith("]")) {
                            throw new Exception("Invalid format: no ending ] for section name");
                        }
                        sectionName = line.substring(1, line.length() - 1).trim();
                        addSection(sectionName);
                        section = getSection(sectionName);
                    } else {
                        addLineToSection(line, section);
                    }
                }
            }
        }
     
        /** 
         * Return the value of the given key in the given section 
         * @param aSectionName the name of the section 
         * @param aKey the key 
         * @return the value if found or null. 
         */
        public String getProperty(String aSectionName, String aKey) {
            Hashtable section = getSection(aSectionName);
            if (null == section) {
                return null;
            }
            return (String) section.get(aKey);
        }
     
        /**
         * @param _section
         * @param _name
         * @param _value
         */
        public void setProperty(String _section, String _name, String _value) {
            HashMap hMap = (HashMap) this.sectionMap.get(_section);
            if (hMap == null) {
                this.newPairMap = new HashMap();
                this.newPairMap.put(_name, _value);
                this.sectionMap.put(_section, this.newPairMap);
            } else {
                hMap.put(_name, _value);
            }
        }
     
        public void removeProperty(String _section, String _name) {
            HashMap hMap = (HashMap) this.sectionMap.get(_section);
            hMap.remove(_name);
        }
     
        /**
         * 
         * @param aLine
         * @param aSection
         * @throws java.lang.Exception
         */
        private void addLineToSection(String aLine, Hashtable aSection) throws Exception {
            if (null == aLine) {
                return;
            }
     
            if (null == aSection) {
                throw new Exception("No section found to add data");
            }
     
            aLine = aLine.trim();
     
            // lines that starts with ; are comments 
            if (aLine.startsWith(";")) {
                return;
            }
     
            // Avoid the empty lines 
            if (aLine.length() == 0) {
                return;
            }
     
            // The format of a line of data is: key = value 
            StringTokenizer st = new StringTokenizer(aLine, "=");
            if (st.countTokens() != 2) {
                throw new Exception("Invalid format of data: " + aLine);
            }
     
            String key = st.nextToken().trim();
            // a key should not contain spaces 
            for (int index = 0; index < key.length(); index++) {
                if (Character.isWhitespace(key.charAt(index))) {
                    throw new Exception("Invalid format of data: " + aLine);
                }
            }
     
            String value = st.nextToken().trim();
     
            aSection.put(key, value);
        }
     
        /**
         * @param aSectionName
         * @return
         */
        public Hashtable getSection(String aSectionName) {
            return (Hashtable) this.sections.get(aSectionName);
        }
     
        /**
         * @param aSectionName
         */
        public void addSection(String aSectionName) {
            if (null == aSectionName) {
                return;
            }
     
            Hashtable section = getSection(aSectionName);
            if (null == section) {
                section = new Hashtable();
                this.sections.put(aSectionName, section);
            }
        }
     
        /**
         * @param outFile
         */
        public void saveSection() {
            BufferedWriter fw = null;
            try {
                fw = new BufferedWriter(new FileWriter(this.configFilename));
     
                // Write original file to tempfile until section
                try {
                    Iterator it = this.sectionMap.keySet().iterator();
                    while (it.hasNext()) {
                        String section = (String) it.next();
                        // Write header out
                        fw.write("[" + section + "]");
                        fw.newLine();
     
                        HashMap map = (HashMap) this.sectionMap.get(section);
                        Iterator iter = map.keySet().iterator();
                        while (iter.hasNext()) {
                            String name = (String) iter.next();
                            String value = (String) map.get(name);
                            // Write key-value pair out
                            fw.write(name + "=" + value);
                            fw.newLine();
                        }
                    }
                } catch (NullPointerException a) {
                    // File might end before section is found
                }
            } catch (IOException e) {
            } finally {
                try {
                    fw.close();
                } catch (Exception e) {
                }
            }
        }
    }
    J'aimerai obtimiser cette classe et notamment en supprimant une des deux méthodes load(InputStream aStream) et loadSection() qui ont l'air de faire la même chose...

    Quelle est la différence d'utilisation entre un BufferReader et un InputStreamReader ?
    Est-ce que quelqu'un peu m'aider?
    Merci d'avance,

    Bap

  2. #2
    Rédacteur
    Avatar de CyberChouan
    Homme Profil pro
    Directeur technique
    Inscrit en
    Janvier 2007
    Messages
    2 752
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Directeur technique
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Janvier 2007
    Messages : 2 752
    Par défaut
    Comme son nom l'indique, un BufferedReader permet de "bufferiser" un flux en lecture. Dans le cas des fichiers textes, cela permet de lire le texte ligne par ligne avec la méthode "readline()", qui n'existe pas dans le InputStreamReader.
    Avant de poster, pensez à regarder la FAQ, les tutoriaux, la Javadoc (de la JRE que vous utilisez) et à faire une recherche
    Je ne réponds pas aux questions techniques par MP: les forums sont faits pour ça
    Mes articles et tutoriaux & Mon blog informatique

Discussions similaires

  1. Réponses: 7
    Dernier message: 15/05/2008, 13h01
  2. BufferReader
    Par pikajojo dans le forum JBuilder
    Réponses: 3
    Dernier message: 11/04/2006, 18h21

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo