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

Java Discussion :

Lire fichier CSV, caractères non reconnus


Sujet :

Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre habitué
    Inscrit en
    Mars 2011
    Messages
    10
    Détails du profil
    Informations forums :
    Inscription : Mars 2011
    Messages : 10
    Par défaut Lire fichier CSV, caractères non reconnus
    Bonjour,

    j'ai trouvé une classe (merci Glob) de lecture de fichier CSV dont voici le code :
    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
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.io.Writer;
    import java.nio.charset.Charset;
    import java.util.Vector;
     
    /**
     * @author Glob
     * @version 0.1
     */
    public class CSVFile {
     
       private int m_rowsCount;
       private int m_colsCount;
       private Vector m_fileContent;
       private final static char CELL_SEPARATOR = ';';
     
       /**
        * Method CSVFile.
        * @param path le chemin du fichier à parser.
        * @throws FileNotFoundException si le fichier spécifié n'existe pas.
        */
       public CSVFile(String path) throws FileNotFoundException {
          m_fileContent = new Vector();
          InputStreamReader fileReader = new InputStreamReader(new FileInputStream(path), Charset.forName("UTF-8"));
         // FileReader fileReader = new FileReader(path);
          readFromFile(fileReader);
          fitVectorsToSize();
       }
     
       /**
        * Method CSVFile.
        * @param reader un reader dans lequel on lit le fichier CSV.
        */
       public CSVFile(Reader reader) {
          m_fileContent = new Vector();
          readFromFile(reader);
          fitVectorsToSize();
       }
     
       private void fitVectorsToSize() {
          m_fileContent.setSize(getRowsCount());
          int fileSize = getRowsCount();
          int colCount = getColsCount();
          for (int i = 0; i < fileSize; i++) {
             Vector aRow = (Vector)m_fileContent.get(i);
             if (aRow == null) {
                m_fileContent.set(i, new Vector());
                aRow = (Vector)m_fileContent.get(i);
             }
             aRow.setSize(colCount);
          }
       }
     
       /**
        * Method readFromFile.
        * @param path
        */
       private void readFromFile(Reader reader) {
          BufferedReader buffReader = new BufferedReader(reader);
          if (buffReader != null) {
             try {
                String tempLine;
                tempLine = buffReader.readLine();
                while (tempLine != null) {
                   readFromLine(tempLine);
                   tempLine = buffReader.readLine();
                }
             } catch (IOException e) {
                System.err.println("Error reading CSV file: " + e.toString());
             } finally {
                try {
                   buffReader.close();
                } catch (IOException e) {
                   System.err.println(
                      "Erreur closing CSV file: "
                      + e.toString()
                   );
                }
             }
          }
          System.runFinalization();
          System.gc();
       }
     
       /**
        * Method readFromLine.
        * @param tempLine
        */
       private void readFromLine(String tempLine) {
          if (tempLine == null) {
             return;
          }
          Vector currentLine = new Vector();
          m_fileContent.add(currentLine);
          m_rowsCount++;
    //      setRowsCount(getRowsCount() + 1);
          if (tempLine.trim().length() == 0) {
             return;
          }
          int colCount = 0;
          int cursorBegin = 0;
          int cursorEnd = tempLine.indexOf(CELL_SEPARATOR);
          while (cursorBegin > -1) {
             if (cursorEnd == -1) {
                currentLine.add(tempLine.substring(cursorBegin));
                cursorBegin = cursorEnd;
             } else {
                currentLine.add(tempLine.substring(cursorBegin, cursorEnd));
                cursorBegin = cursorEnd + 1;
             }
             cursorEnd = tempLine.indexOf(CELL_SEPARATOR, cursorBegin);
             colCount++;
          }
          if (colCount > getColsCount()) {
             setColsCount(Math.max(getColsCount(), colCount));
          }
       }
     
     
       /**
        * Returns the colsCount.
        * @return int
        */
       public int getColsCount() {
          return m_colsCount;
       }
     
       /**
        * Returns the rowsCount.
        * @return int
        */
       public int getRowsCount() {
          return m_rowsCount;
       }
     
       /**
        * Sets the colsCount.
        * @param colsCount The colsCount to set
        */
       public void setColsCount(int colsCount) {
          m_colsCount = colsCount;
          fitVectorsToSize();
       }
     
       /**
        * Sets the rowsCount.
        * @param rowsCount The rowsCount to set
        */
       public void setRowsCount(int rowsCount) {
          m_rowsCount = rowsCount;
          fitVectorsToSize();
       }
     
       /**
        * Method getData.
        * @param row la ligne voulue
        * @param col la colonne voulue
        * @return String la valeur à l'enplacement spécifié. Null si outOfBound.
        */
       public String getData(int row, int col) {
          if (row < 0
             || col < 0
             || row > (getRowsCount() - 1)
             || col > (getColsCount() - 1)) {
             return null;
          }
          try {
             Vector theRow = (Vector)m_fileContent.get(row);
             String result = (String)theRow.get(col);
             return (result == null ? "" : result);
          } catch (IndexOutOfBoundsException e) {
             return "";
          }
       }
     
       /**
        * Method setData.
        * @param row le numéro de ligne (commence à 0).
        * @param col le numéro de colonne (commence à 0).
        * @param data les données à insérer.
        */
       public void setData(int row, int col, String data) {
          if (row < 0
             || col < 0
             || row > (getRowsCount() - 1)
             || col > (getColsCount() - 1)) {
             throw new IndexOutOfBoundsException();
          }
          Vector theRow = (Vector)m_fileContent.get(row);
          theRow.setElementAt(data, col);
       }
     
       /**
        * Method write.
        * @param filePath le fichier dans lequel sauver les données.
        * @throws IOException si une erreur survient.
        */
       public void write(String filePath) throws IOException {
          FileWriter fileWriter = new FileWriter(filePath);
          write(fileWriter);
       }
     
       /**
        * Method write.
        * @param aWriter le writer dans lequel on veut écrire les données.
        * @throws IOException si une erreur survient.
        */
       public void write(Writer aWriter) throws IOException {
          BufferedWriter writer;
          writer = new BufferedWriter(aWriter);
          int fileSize = getRowsCount();
          int colCount = getColsCount();
          for (int i = 0; i < fileSize; i++) {
             for (int j = 0; j < colCount; j++) {
                writer.write(getData(i, j));
                if (j + 1 < colCount) {
                   writer.write(CELL_SEPARATOR);
                }
             }
             if (i + 1 < fileSize) {
                writer.write("\n");
             }
          }
          writer.flush();
          writer.close();
       }
    }
    vous voyez que j'ai remplacé la ligne comme exactement indiqué ici mais malheuresement cela ne marche toujours pas. (ligne 32 et 33)
    et j'ai toujours les "???".
    j'espère que quelqu'un pourrait m'aider.
    merci d'avance.

  2. #2
    Rédacteur/Modérateur
    Avatar de Logan Mauzaize
    Homme Profil pro
    Architecte technique
    Inscrit en
    Août 2005
    Messages
    2 894
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Architecte technique
    Secteur : Transports

    Informations forums :
    Inscription : Août 2005
    Messages : 2 894
    Par défaut
    C'est que ton fichier en entrée n'est pas encodé en "UTF-8"

    Concernant la lecture/écriture du CSV il manque deux caractéristiques: saut de lignes et séparateur dans une valeur
    Java : Cours et tutoriels - FAQ - Java SE 8 API - Programmation concurrente
    Ceylon : Installation - Concepts de base - Typage - Appels et arguments

    ECM = Exemple(reproduit le problème) Complet (code compilable) Minimal (ne postez pas votre application !)
    Une solution vous convient ? N'oubliez pas le tag
    Signature par pitipoisson

  3. #3
    Membre habitué
    Inscrit en
    Mars 2011
    Messages
    10
    Détails du profil
    Informations forums :
    Inscription : Mars 2011
    Messages : 10
    Par défaut
    Oui vous avez raison!
    Mais je ne comprend pas...Lorsque je déclare le fichier en utf-8 et que je crée un nouveau fichier, il est reconnu comme encodé en ANSI avec le bloc note Windows.

    Pourquoi n'est-il pas en utf-8 ?
    et comment pourrais-je trouver le nom canonique de ANSI ?

    merci d'avance.

  4. #4
    Rédacteur/Modérateur
    Avatar de Logan Mauzaize
    Homme Profil pro
    Architecte technique
    Inscrit en
    Août 2005
    Messages
    2 894
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Architecte technique
    Secteur : Transports

    Informations forums :
    Inscription : Août 2005
    Messages : 2 894
    Par défaut
    Faut pas se fier au bloc-notes, il utilise ces propres algorithmes pour "deviner" l'encodage. Seul celui qui a généré le fichier sait quel encodage a été utilisé. Si tu l'as généré en UTF-8 alors c'est de l'UTF-8.

    Le petit nom pour "ANSI" c'est "CP-1252" ou "Cp1252" dans la JVM.
    Java : Cours et tutoriels - FAQ - Java SE 8 API - Programmation concurrente
    Ceylon : Installation - Concepts de base - Typage - Appels et arguments

    ECM = Exemple(reproduit le problème) Complet (code compilable) Minimal (ne postez pas votre application !)
    Une solution vous convient ? N'oubliez pas le tag
    Signature par pitipoisson

Discussions similaires

  1. lire fichier csv
    Par nico0812 dans le forum C#
    Réponses: 4
    Dernier message: 17/04/2007, 18h40
  2. lire fichier csv et en extraire des infos
    Par isaglada dans le forum VBScript
    Réponses: 2
    Dernier message: 12/02/2007, 13h04
  3. [Compilation]Fichiers d'inclusion non reconnus
    Par Pépé Lélé dans le forum Autres éditeurs
    Réponses: 3
    Dernier message: 04/03/2006, 13h00
  4. Réponses: 21
    Dernier message: 01/03/2006, 16h51
  5. [PHP & Oracle] caractères non reconnus
    Par Ryle dans le forum Oracle
    Réponses: 3
    Dernier message: 08/02/2006, 08h09

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