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

Format d'échange (XML, JSON...) Java Discussion :

Page Sources Java libres - participez ici [Sources]


Sujet :

Format d'échange (XML, JSON...) Java

  1. #41
    Membre émérite
    Avatar de xavlours
    Inscrit en
    Février 2004
    Messages
    1 832
    Détails du profil
    Informations forums :
    Inscription : Février 2004
    Messages : 1 832
    Points : 2 410
    Points
    2 410
    Par défaut
    Et voici une classe qui évite de se taper les éternels JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE), JFrame.setLocationRelativeTo(null), etc. Je l'utilise tout le temps.
    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
    package divers;
     
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JMenuBar;
     
    public class DisplayUtils {
     
        public static void prepareAndShow(JFrame frame) {
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setVisible(true);
        }
     
        public static JFrame displayInFrame(JComponent comp) {
            return displayInFrame(comp, null, null);
        }
     
        public static JFrame displayInFrame(JComponent comp, String title, JMenuBar menuBar) {
            if(title == null)
                title = "";
            JFrame frame = new JFrame(title);
            if(menuBar != null)
                frame.setJMenuBar(menuBar);
            frame.setContentPane(comp);
            prepareAndShow(frame);
            return frame;
        }
     
    }
    "Le bon ni le mauvais ne me feraient de peine si si si je savais que j'en aurais l'étrenne." B.V.
    Non au langage SMS ! Je ne répondrai pas aux questions techniques par MP.
    Eclipse : News, FAQ, Cours, Livres, Blogs.Et moi.
      0  0

  2. #42
    Membre confirmé Avatar de broumbroum
    Profil pro
    Inscrit en
    Août 2006
    Messages
    406
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : Suisse

    Informations forums :
    Inscription : Août 2006
    Messages : 406
    Points : 465
    Points
    465
    Par défaut Object Cache Manager rapide
    Voici un code de management de cache d'objets (adapté aux sprites graphiques pour le jeu), originalement inspiré du code SoftCache d'IBM (plus complexe dans la lisibilité): (désolé pour les qqs commentaires en anglais j'ai pas toujours le reflexe en français )


    En général, les erreurs de memory overflow (OutOfMemory Exceptions) disparaissent quand le cache est bien adapté.... Bref, il y a pas mal de lignes de code mais il me semble complet bien que je tombe encore sur des overflow mémoire en ce moment...
    Peut-être que la capacité des LRU et MRU de type LIFO et FIFO du cache est à revoir. (n.d.r. c'est LIFO et HIFO resp.)
    Attachement: Une démo du cache avec une animation sprites au format .png (c'est un fichier de chargement WebStart, donc pas énorme. )
    Fichiers attachés Fichiers attachés
      0  0

  3. #43
    Membre confirmé Avatar de broumbroum
    Profil pro
    Inscrit en
    Août 2006
    Messages
    406
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : Suisse

    Informations forums :
    Inscription : Août 2006
    Messages : 406
    Points : 465
    Points
    465
    Par défaut A propos du cache manager
    Il se compose dorénavant de toutes les fonctions nécessaires que l'on pourrait imaginer pour un cache en Java. Je dis ça parce que je n'observe plus de ralentissement ni de "blocking", or il se trouve que certaines version de ce cache n'implémentent pas les mêmes fonctions, telles que le "swap" ou la compression zip.
    Il faut s'assurer de n'avoir pas oublié d'implémenter les objets destinés à être cachés avec une interface Serializable. Celle-ci permet en effet le swap et la compression. Autrement seule la mise en cache virtuelle est possible, ce qui réduit la capacité de stockage du cache.
    Ensuite, il faut penser à faire des callbacks sur chaque méthode nécessitant un ajustement précis en mémoire puis également utiliser les fonctions add et get pour accéder au cache.
    La dernière option, est celle du rafraichissement en boucle du Garbage Collector, qui peut être forcé avec setAutoCleanupEnabled().

    Finalement, il est nécessaire d'accorder une capacité suffisante aux listes LIFO HIFO (? passez moi les termes de gestion... ) afin d'être tranquille quant aux erreurs heap space.

    En conclusion, il existe de nombreuses méthodes de conception d'un cache mémoire en java et celui-ci se veut simple et direct, sans pour autant vouloir entrer dans le détail d'un cache infiniment paramétrable. OSCache, SoftCache sont des références opensource que vous pouvez également consulter si l'envie de personnaliser les fonctions vous intéresse.

    VOILA C TOUT J ESPERE NE PAS AVOIR TROP DE MODIF A FAIRE PAR LA SUITE.......
    Images attachées Images attachées  
      0  0

  4. #44
    Candidat au Club
    Profil pro
    Inscrit en
    Mars 2007
    Messages
    4
    Détails du profil
    Informations personnelles :
    Âge : 60
    Localisation : France

    Informations forums :
    Inscription : Mars 2007
    Messages : 4
    Points : 4
    Points
    4
    Par défaut Charger un fichier Excel dans une base Ms Access
    Bonjour,

    Je viens par le présent message remercier toutes les personnes qui ont répondu aux questions d’autres développeurs bloqués durant leur développement JAVA. Je m’initie actuellement à l’écriture de programme JAVA, et j’ai trouvé une aide précieuse sur ce site. Pour se faire, je viens déposer ma contribution pour les futurs développeurs JAVA.

    Mes principaux problèmes étaient de lire un fichier Excel pour enregistrer les données dans une base MS Access. De ce fait, j’ai rencontré un certain nombre de problèmes. Je vais lister des mots clés qui m’ont permis de trouver les informations requises sur le Net afin de faciliter la recherche.
    • Lecture / Connection / Déclaration / MS Access
    • Lecture / Connection / Déclaration / Fichier Excel grâce à « JexcelApi »
    • Formater les décimales avec une virgules / Remplacer un point par une virgule pour la décimale avec java.text.NumberFormat
    • Formater une date / Format date AAAA/MM/JJ / Format date yyyy/MM/dd avec java.text.DateFormat
    • Créer / Déclarer / une base MS Access dans ODBC sous Windows


    1. L’installation de « JexcelApi » :
      Après avoir récupérer le fichier sur le site http://jexcelapi.sourceforge.net/, créer un sous répertoire « jexcelapi » dans votre répertoire « Java ». Copier l’ensemble du fichier « .zip ». Ajouter le fichier « jxl.jar » avec son chemin complet dans votre CLASSPATH (Poste de travail => Avancé => Variable d’environnement => Variable système).

    2. Configuration d’ODBC sous Winsows :
      Tout d’abord, nous avons accès sur nos Pc à cet outil de la manière suivante : Démarrer => Paramètres => Panneau de configuration => Outil d’administration => Source de données ODBC.
      S’il vous manque des pilotes ODBC, vous devrez faire comme moi, les chercher sur le Net.

    3. Formater en fonction des paramètres régionaux de votre Pc :
      Suivant les cas, vous aurez besoin de transformer le point décimal par une virgule décimale, ajouter le symbole monétaire correspondant à votre pays, afficher une date dans un format spécifique ou un pourcentage. Vous trouverez de l’aide avec l’url http://java.sun.com/developer/TechTi...0/tt0411.html.

    Pour finir, je colle mon programme dans ce message afin de vous aider à comprendre les différentes classes. Certains diront qu’il est possible d’optimiser certaines commandes, alors je leur serai grès de bien vouloir préciser comment avec la reprise de mon code.

    Merci à tous pour votre lecture.

    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
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
     
    import java.io.File;
    import java.io.IOException;
     
    import jxl.Workbook;
    import jxl.Sheet;
    import jxl.Cell;
    import jxl.CellType;
    import jxl.DateCell;
    import jxl.LabelCell;
    import jxl.NumberCell;
     
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.SQLException;
    import java.sql.ResultSet;
    import java.sql.DriverManager;
     
    import java.util.Date;
    import java.util.Locale;
     
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
     
     
     
    public class T07_LectureExcel extends Frame implements ActionListener, WindowListener
    {
    	// ---------------------------------------
    	// Variable communes
    	// ---------------------------------------
     
    	TextArea TarTexte = new TextArea();	// La zone de TarTexte pour l'affichage
    	String StrgEdit = "";			// Zone de conservation d'affichage
    	Statement StatDB = null;		// Intentiation d'une commande sur la base
    	ResultSet RstQuery = null;		// Résultat d'une resquête SQL
    	String StrgQuery = "";			// Zone de commande SQL
    	int intRes = 0;				// Test ajout enregistrement
     
    	// Definition des formatages français
    	NumberFormat NumForDecimal = NumberFormat.getInstance(Locale.FRENCH);
     	NumberFormat NumForMonnaie = NumberFormat.getCurrencyInstance(Locale.FRENCH);
    	NumberFormat NumForPourcent = NumberFormat.getPercentInstance(Locale.FRENCH);
    	DateFormat dtfDevis = new SimpleDateFormat("yyyy/MM/dd");
     
    	//-----------------------------------------------------------------------
    	// Construction de la class EdText
    	// D‚finition et affichage de la boŒte de dialogue
    	//-----------------------------------------------------------------------
    	T07_LectureExcel()
    	{
    		// Titre de la fenêtre et zone de TarTexte
    		super("Liste de fichiers");
    		add("Center", TarTexte);
     
    		Locale loc = Locale.getDefault();
     
    		// Définition et affichage du système de menus
    		MenuBar mb = new MenuBar();
    		Menu ml = new Menu("Fichier");
    		mb.add(ml);
     
    		// Définition et affichage du système de sous menu du menu 01
    		MenuItem il1 = new MenuItem("Chargement Devis");
    		MenuItem il2 = new MenuItem("Quitter");
    		ml.add(il1);
    		ml.add(il2);
    		setMenuBar(mb);
     
    		il1.setActionCommand("Chargement");
    		il2.setActionCommand("Quitter");
     
    		il1.addActionListener(this);
    		il2.addActionListener(this);
     
    		// Taille par défaut de la Frame
    		setSize(600,350);
    	}
     
    	//-----------------------------------------------------------------------------
    	// Gestion de l'événement Case de fermeture
    	//-----------------------------------------------------------------------------
    	public void windowClosing(WindowEvent event)
    	{
    		System.exit(0);
    	}
    	public void windowClosed(WindowEvent event)
    	{
    	}
    	public void windowDeiconified(WindowEvent event)
    	{
    	}	
    	public void windowIconified(WindowEvent event)
    	{
    	}	
    	public void windowActivated(WindowEvent event)
    	{
    	}	
    	public void windowDeactivated(WindowEvent event)
    	{
    	}	
    	public void windowOpened(WindowEvent event)
    	{
    	}
     
    	//-----------------------------------------------------------------------------
    	// Capture des événements liés au systême de menus
    	//-----------------------------------------------------------------------------
    	public void actionPerformed(ActionEvent evt)
    	{
     
    		//-----------------------------------------------------------------------
    		// Commande Fichier => Chargement Devis
    		//-----------------------------------------------------------------------
    		if (evt.getActionCommand().equals("Chargement"))
    		{
    			FileDialog fichier = new FileDialog(this, "Ouvrir", FileDialog.LOAD);
    			fichier.show();
     
    			String StrgNom = fichier.getFile();
    			String StrgDir = fichier.getDirectory();
     
    			// ---------------------------------------			
    			// Affichage du Contenu du fichier.
    			// ---------------------------------------
    			try
    			{
    				// =====================================
    				// Ouverture de la base MS Access
    				// =====================================
     
    				// Chargement du pilote JDBC
    				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     
    				// URL de connexion
    				String StrgUrl = "jdbc:odbc:2007DB";
     
    				// Connexion
    				Connection ConDB = DriverManager.getConnection(StrgUrl);
     
    				// =====================================
    				// Ouverture du fichier Excel
    				// =====================================
     
    				Workbook WbFichier = Workbook.getWorkbook(new File(StrgDir+StrgNom));
     
    				// Ouverture de la première feuille, la seconde est 1, etc. 
    				Sheet ShtFeuille = WbFichier.getSheet(0); 
     
    				// *************************************
    				// **         TABLE DEVIS             **
    				// *************************************
     
    				// Récupération de la valeur d'une cellule
    				Cell cel01 = ShtFeuille.getCell("J4"); 		// Numéro de devis 
    				Cell cel02 = ShtFeuille.getCell("O2"); 		// Date du devis
    				Cell cel03 = ShtFeuille.getCell("C10"); 	// Nom du contact
    				Cell cel04 = ShtFeuille.getCell("C11"); 	// Nom de la société
    				Cell cel05 = ShtFeuille.getCell("C12"); 	// Adresse 1
    				Cell cel06 = ShtFeuille.getCell("C13"); 	// Adresse 2
    				Cell cel07 = ShtFeuille.getCell("Q9"); 		// Classe tarif
    				Cell cel08 = ShtFeuille.getCell("R9"); 		// Coefficient tarif
    				Cell cel09 = ShtFeuille.getCell("Q12"); 	// Nombre de mois gratuit
    				Cell cel10 = ShtFeuille.getCell("Q14"); 	// Durée du contrat
     
    				// Convertion de données
    				double DblNumDevis = 0;
    				String StrgNumDevis = "";
    				Date dtDevis = null;
    				String StrgNomContact = "";
    				String StrgNomSociete = "";
    				String StrgNomAdresse1 = "";
    				String StrgNomAdresse2 = "";
    				String StrgClasseTarif = "";
    				double dblCoefTarif = 0;
    				double dblNbMoisGratuit = 0;
    				double dblDureeContrat = 0;
     
    				// ---------------------------------
    				// Contrôle du format de la cellule
    				// ---------------------------------
     
    				// 01 - Vérifie si la valeur est un nombre
    				if (cel01.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel01; 
    					DblNumDevis = nc.getValue();
    					StrgNumDevis = "" + (int) DblNumDevis;
    				}
     
    				// 01 - Vérifie si la valeur est une chaîne
    				if (cel01.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel01; 
    					StrgNumDevis = lc.getString(); 
    				} 
     
    				// 02 - Vérifie si la valeur est un date 
    				if (cel02.getType() == CellType.DATE) 
    				{ 
    					DateCell dc = (DateCell) cel02; 
    					dtDevis = dc.getDate();
    				} 
     
    				// 03 - Vérifie si la valeur est une chaîne
    				//if (cel03.getType() != CellType.EMPTY) 
     
    				if (cel03.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel03; 
    					StrgNomContact = lc.getString(); 
    				}
     
    				// 04 - Vérifie si la valeur est une chaîne
    				if (cel04.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel04; 
    					StrgNomSociete = lc.getString(); 
    				}
     
    				// 05 - Vérifie si la valeur est une chaîne
    				if (cel05.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel05; 
    					StrgNomAdresse1 = lc.getString(); 
    				}
     
    				// 06 - Vérifie si la valeur est une chaîne
    				if (cel06.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel06; 
    					StrgNomAdresse2 = lc.getString(); 
    				}
     
    				// 07 - Vérifie si la valeur est une chaîne
    				if (cel07.getType() == CellType.LABEL) 
    				{ 
    					LabelCell lc = (LabelCell) cel07; 
    					StrgClasseTarif = lc.getString(); 
    				}
     
    				// 08 - Vérifie si la valeur est un nombre
    				if (cel08.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel08; 
    					dblCoefTarif = nc.getValue(); 
    				}
     
    				// 09 - Vérifie si la valeur est un nombre
    				if (cel09.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel09; 
    					dblNbMoisGratuit = nc.getValue(); 
    				}
     
    				// 10 - Vérifie si la valeur est un nombre
    				if (cel10.getType() == CellType.NUMBER) 
    				{ 
    					NumberCell nc = (NumberCell) cel10; 
    					dblDureeContrat = nc.getValue(); 
    				}
     
    				// Affichage de la sélection dans l'éditeur
    				StrgEdit =	"*************************" + "\n" +
    						"**      TABLE DEVIS    **" + "\n" +
    						"*************************" + "\n" +
    						"Fichier                : " + StrgDir+StrgNom + "\n" +
    						"Numéro de devis        : " + StrgNumDevis + "\n" + 
    						"Date du devis          : " + dtfDevis.format(dtDevis) + "\n" +
    						"Contact                : " + StrgNomContact + "\n" + 
    						"Nom de la société      : " + StrgNomSociete + "\n" + 
    						"Ligne n°1 de l'adresse : " + StrgNomAdresse1 + "\n" + 
    						"Ligne n°2 de l'adresse : " + StrgNomAdresse2 + "\n" + 
    						"Classe tarif           : " + StrgClasseTarif + "\n" + 
    						"Coefficient tarif      : " + NumForDecimal.format(dblCoefTarif) + "\n" + 
    						"Nombre de mois gratuit : " + (int) dblNbMoisGratuit + "\n" + 
    						"Durée du contrat       : " + (int) dblDureeContrat + "\n\n";
    				TarTexte.setText(StrgEdit);
     
    				// Affichage de la requête dans l'éditeur
    				StrgEdit = StrgEdit +	"********************************" + "\n" +
    							"**  CONTROLE DU DEVIS  **" + "\n" +
    							"********************************" + "\n\n";
     
    				// Construction de la requête de selection
    				StrgQuery = "SELECT Devis.* FROM Devis WHERE Devis.NumDevis = '" + StrgNumDevis + "'";
    				StrgEdit = StrgEdit + StrgQuery + "\n\n";
     
    				// Contrôle d'existance du devis dans la table DEVIS
    				// -> Penser à déclarer les Field Summary pour utiliser certaines méthodes 
    				StatDB = ConDB.createStatement(	ResultSet.TYPE_SCROLL_INSENSITIVE, 
    								ResultSet.CONCUR_UPDATABLE );
    				RstQuery = StatDB.executeQuery(StrgQuery);
     
    				// Positionner le curseur en fin de sélection
    				RstQuery.last();
    				// Récupérer le nombre de lignes
    				int intRes = RstQuery.getRow();
    				// Re positionner le curseur au début de sélection
    				RstQuery.first();
     
    				// Test si un enregistrement est trouvé
    				if (intRes == 0)
    				{
    					// Initialisation du nouvel enregistrement dans la table DEVIS
    					StrgQuery = "INSERT INTO Devis VALUES ( '" + StrgNumDevis + "', " +
    										"'" + dtfDevis.format(dtDevis) + "', " +
    										"'" + StrgDir+StrgNom + "', " +
    										"'" + StrgNomContact + "', " +
    										"'" + StrgNomSociete + "', " + 
    										"'" + StrgNomAdresse1 + "', " + 
    										"'" + StrgNomAdresse2 + "', " + 
    										"'" + StrgClasseTarif + "', " + 
    										"'" + NumForDecimal.format(dblCoefTarif) + "', " +
    										"'" + (int) dblNbMoisGratuit + "', " + 
    										"'" + (int) dblDureeContrat + "', " + 
    										"'" + dtfDevis.format(new Date()) +
    										"', null, null)";										
    					StrgEdit = StrgEdit + StrgQuery + "\n\n";
     
    					// Enregistrement du nouvel enregistrement dans la table DEVIS
    					intRes = StatDB.executeUpdate(StrgQuery);
     
    					// Test si l'enregistrement a bien été enregistré
    					if (intRes == 1 )
    						StrgEdit = StrgEdit + "Nouveau devis '" + StrgNumDevis + "' crée dans la table DEVIS. \n\n";
    				}
    				else
    					StrgEdit = StrgEdit + "Le devis '" + StrgNumDevis + "' existe déjà dans la table DEVIS. \n\n";							
     
     
    				// Affichage de la requête dans l'éditeur
    				TarTexte.setText(StrgEdit);
     
    				// ---------------------------------------
    				// Fermeture du fichier
    				// ---------------------------------------
    				WbFichier.close();
    				ConDB.close();
    			}
     
    			// ---------------------------------------			
    			// Gestion des erreurs
    			// ---------------------------------------
    			catch(jxl.read.biff.BiffException biffE)
    			{ 
    				biffE.printStackTrace();
    				System.exit(1);
    			}
    			catch(IOException ioe)
    			{ 
    				ioe.printStackTrace();
    				System.exit(1);
    			}
    			catch(ClassNotFoundException cnfee) 
    			{
    				cnfee.printStackTrace();
    				System.exit(1);
    			}
    			catch(SQLException sqle) 
    			{
    				System.out.println("SQLException : " + sqle.getErrorCode());
    				switch (sqle.getErrorCode())
    				{
    					default :
    					{
    						sqle.printStackTrace();
    						System.exit(1);
    					}
    				}
    			}
     
    		}
     
    		//-----------------------------------------------------------------------
    		// Commande Fichier/Quitter
    		//-----------------------------------------------------------------------
    		if (evt.getActionCommand().equals("Quitter"))
    		{
    			System.exit(0);
    		}
    	}
     
    	//----------------------------------------------------------------------------------
    	// D‚finition d'une frame pour l'application et affichage de la
    	// boŒte de dialogue
    	//----------------------------------------------------------------------------------
    	public static void main(String args[])
    	{
    		T07_LectureExcel editer = new T07_LectureExcel();
    		editer.show();
    		editer.addWindowListener(editer);
    	}		
    }
      0  0

  5. #45
    Membre habitué Avatar de ludosoft
    Homme Profil pro
    Chef de projet technique
    Inscrit en
    Juillet 2002
    Messages
    99
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Chef de projet technique
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juillet 2002
    Messages : 99
    Points : 136
    Points
    136
    Par défaut Comment (dé)sérialiser des données PHP avec Java ?
    Il peut arriver d'avoir besoin de faire communiquer un script PHP avec un programme Java. Il existe bien entendu tout un tas de techniques (services Web et autres sérialisations XML) mais il arrive parfois que l'on soit obligé de composer avec les fonctions "serialize" et "unserialize" de PHP.

    Après de longues recherches sur le net je n'ai rien trouvé de vraiment très probant pour "(dé)coder" le format de données sérialisées de PHP.

    J'ai donc développé une petite classe que j'ai déposé sur java.net :
    https://phpserializer.dev.java.net/s...va?view=markup

    Petit exemple d'utilisation de ma classe :
    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
    try{
     
            //Some "Java" data
            List javaData=new ArrayList();
            javaData.add("a test string");
            javaData.add(50);
            javaData.add(32.56f);
            javaData.add(6541L);
     
            PHPSerializer serializer=new PHPSerializer();
     
            //Serialize
            String serializedData=serializer.serialize(javaData);
            System.out.println("Serialized data : "+serializedData);
     
            //Unserialize
            Object data=serializer.unserialize(serializedData);
            System.out.println("Unserialized data : "+data);
     
        }catch(Exception ex){
            System.err.println("Oh my god... "+ex);
        }
    Ce qui donne la sortie suivante :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    Serialized data : a:4:{i:0;s:13:"a test string";i:1;i:50;i:2;d:32.56;i:3;i:6541;}
    Unserialized data : {0=a test string, 1=50, 2=32.56, 3=6541}
    Accès anonyme au CVS :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    cvs -d :pserver:guest@cvs.dev.java.net:/cvs checkout phpserializer
    Et un d'plus en moins !
      0  0

  6. #46
    Membre actif
    Avatar de JMLLB
    Inscrit en
    Septembre 2006
    Messages
    285
    Détails du profil
    Informations forums :
    Inscription : Septembre 2006
    Messages : 285
    Points : 268
    Points
    268
    Par défaut extension des JButton pour png transparents
    Bonjour,

    Pour les besoins d'une application que je développe, j'ai codé deux petites classes étendant JButton qui me permettent de changer les couleurs d'un bouton sans changer l'image.
    Avec un bouton rond de type "glassy" en png par exemple, je peux changer sa couleur standard, de selection, de rollover et de fond sans retoucher à l'image.
    Si on utilise la classe JButton telle quel on est obliger de choisir la couleur du bouton une fois pour toute et d'avoir autant d'image que cas de figure (rollover, selected...).
    Ce n'est pas pratique dans les phases de test des LnF et de changement de look des IHM.

    Si vous pensez que ça peut être interessant dans le cadre source Java, voici les sources ainsi que qq png glassy pour essai.

    cordialement,

    JMLLB

    ISButton.java:
    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
     
    /*
     * ISButton.java
     *
     * Created on 15 décembre 2006, 16:28
     */
     
    package Main;
     
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    import java.awt.image.BufferedImage;
     
    /**
     * This class allows to change Foreground, Background and Selection color
     * on a JButton with an Icon. It gives maximum effect with transparent image.
     * The shape of the foreground is a Rectangle of the same size of the icon,
     * the JButton is supposed to be 1.5 bigger than the icon and fill with the background color.
     * When selected the Foregroud color is replaced by the Selection color.
     * When the JButton is pressed the pressedIcon (if set) is displayed only with the Background color.
     *
     * @author JMLLB
     */
    public class ISButton extends JButton{
     
        /** Foreground, Background and Selection color. */
        private Color foregroundColor,backgroundColor,selectionColor;
        /** Icon of the button. */
        private Icon icon;
     
        /** Creates a new instance of ISButton */
        public ISButton(){
            super();
            this.setBorderPainted(false);
            this.setFocusPainted(false);
            this.foregroundColor=Color.BLUE;
            this.backgroundColor=Color.WHITE;
            this.selectionColor=Color.PINK;
            this.setContentAreaFilled(false);
        }
     
        /** Creates a new instance of ISButton */
        public ISButton(String text_in) {
            super(text_in);
            this.setBorderPainted(false);
            this.setFocusPainted(false);
        }
     
        /** Creates a new instance of ISButton */
        public ISButton(Icon icon_in) {
            super(icon_in);
            this.setBorderPainted(false);
            this.setFocusPainted(false);
            this.icon=icon_in;
        }
     
        /** Creates a new instance of ISButton */
        public ISButton(String text_in, Icon icon_in) {
            super(text_in,icon_in);
            this.setBorderPainted(false);
            this.setFocusPainted(false);
            this.icon=icon_in;
        }
     
        /** Reset the icon */
        public void resetIcon(){
            this.setIcon(this.icon);
        }
     
        /** Set a new icon */
        public void setIcon(Icon icon_in){
            if(icon_in==null){
                super.setIcon(icon_in);
            }else{
     
                /** Set the size to 1.5 time the icon size*/
                this.setPreferredSize(new Dimension((int) (icon_in.getIconWidth()*1.05),(int) (icon_in.getIconHeight()*1.05)));
                this.setMaximumSize(new Dimension((int) (icon_in.getIconWidth()*1.05),(int) (icon_in.getIconHeight()*1.05)));
                this.setMinimumSize(new Dimension((int) (icon_in.getIconWidth()*1.05),(int) (icon_in.getIconHeight()*1.05)));
                /** Set the new icon */
                this.icon=icon_in;
                /** Draw the standart BufferedImage with ForegroundColor. */
                BufferedImage bImage0= colorizeImage(icon_in,this.getForeground());
                super.setIcon(new ImageIcon(bImage0));
                /** Draw the rollover BufferedImage with lighter ForegroundColor. */
                BufferedImage bImage1= colorizeImage(icon_in,this.getForeground(125));
                super.setRolloverIcon(new ImageIcon(bImage1));
                /** Draw the selected BufferedImage with lighter SelectionColor. */
                BufferedImage bImage2= colorizeImage(icon_in,this.getSelectionColor());
                super.setSelectedIcon(new ImageIcon(bImage2));
                super.setRolloverSelectedIcon(new ImageIcon(bImage2));
            }
        }
     
        /** Shunt the setRolloverIcon method */
        public void setRolloverIcon(Icon icon_in){ 
        }
     
        /** Shunt the setSelectedIcon method */
        public void setSelectedIcon(Icon icon_in){
        }
     
        /** return the BufferedImage with the appropriate color */
        public BufferedImage colorizeImage(Icon icon_in, Color color_in){  
     
            // Create a new BufferedImage.     
            BufferedImage bImage= new BufferedImage(
                icon_in.getIconWidth(),
                icon_in.getIconHeight(),
                BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic2D = (Graphics2D) bImage.getGraphics();
     
            // Turn on antialiasing.
            graphic2D.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
     
            // Fill with the choosen color.  
            graphic2D.setPaint(color_in);
            graphic2D.fillRect(
                    0,
                    0,
                    (int) (bImage.getWidth()),
                    (int) (bImage.getHeight())
                    );
     
            // Draw the icon on the BufferedImage.  
            icon_in.paintIcon(null,bImage.getGraphics(),0,0);
     
            return bImage;
        }
     
        // Set the Foreground color.
        public void setForeground(Color color_in){
            this.foregroundColor=color_in;
            super.setForeground(color_in);
        }
     
        // Set the Background color.
        public void setBackground(Color color_in){
            this.backgroundColor=color_in;
            super.setBackground(color_in);
        }
     
        // Set the Selection color.
        public void setSelectionColor(Color color_in){
            this.selectionColor=color_in;
        }
     
        // Get the Foreground color.
        public Color getForeground(){
            return(this.foregroundColor);
        }
     
        // Get the Background color.
        public Color getBackground(){
            return(this.backgroundColor);
        }
     
        // Get the Selection color.
        public Color getSelectionColor(){
            return(this.selectionColor);
        }
     
        // Get the Foreground color with modificator (0xFF=>white 0x00=>no change).
        public Color getForeground(int modificator_in){
            return(modificateColor(this.foregroundColor, modificator_in));
        }
     
        // Get the Background color with modificator (0xFF=>white 0x00=>no change).
        public Color getBackground(int modificator_in){
            return(modificateColor(this.backgroundColor, modificator_in));
        }
     
        // Get the Selection color with modificator (0xFF=>white 0x00=>no change).
        public Color getSelectionColor(int modificator_in){
            return(modificateColor(this.selectionColor, modificator_in));
        }
     
        // Return modified color (0xFF=>white 0x00=>no change).
        public static Color modificateColor(Color color_in, int modificator_in){
            if(color_in!=null){
                int r,g,b;
                r=Math.max(0,Math.min(0xFF,color_in.getRed()+modificator_in));
                g=Math.max(0,Math.min(0xFF,color_in.getGreen()+modificator_in));
                b=Math.max(0,Math.min(0xFF,color_in.getBlue()+modificator_in));
                return(new Color(r,g,b));
            }else{
                return(null);
            }
        }
    }
    ISButtonEllipse.java:
    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
     
    /*
     * ISButtonEllipse.java
     *
     * Created on 25 décembre 2006, 15:16
     */
     
    package Main;
     
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    import java.awt.image.BufferedImage;
     
     
    /**
     * This class allows to change Foreground, Background and Selection color
     * on a JButton with an Icon just as ISButton but with a different shape.
     * The shape of the foreground is an Ellipse of the same width and height than the icon.
     *
     * @author JMLLB
     */
    public class ISButtonEllipse extends ISButton {
     
        /** Creates a new instance of ISButtonEllipse */
        public ISButtonEllipse(){
            super();
        }
     
        /** Creates a new instance of ISButtonEllipse */
        public ISButtonEllipse(String text) {
            super(text);
        }
     
        /** Creates a new instance of ISButtonEllipse */
        public ISButtonEllipse(Icon icon_in) {
            super(icon_in);
        }
     
        /** Creates a new instance of ISButtonEllipse */
        public ISButtonEllipse(String text, Icon icon_in) {
            super(text,icon_in);
        }
     
        /** return the BufferedImage with the appropriate color */
        public BufferedImage colorizeImage(Icon icon_in, Color color_in){     
     
            // Create a new BufferedImage.   
            BufferedImage bImage= new BufferedImage(
                icon_in.getIconWidth(),
                icon_in.getIconHeight(),
                BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic2D = (Graphics2D) bImage.getGraphics();
     
            // Turn on antialiasing.
            graphic2D.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
     
            // Fill with the Background color.  
            graphic2D.setPaint(this.getBackground());
            graphic2D.fillRect(
                    0,
                    0,
                    (int) (bImage.getWidth()),
                    (int) (bImage.getHeight())
                    );
     
            // Fill the ellipse with the choosen color.  
            graphic2D.setPaint(color_in);
            graphic2D.fillOval(
                    0,
                    0,
                    (int) (bImage.getWidth()),
                    (int) (bImage.getHeight())
                    );
     
            // Draw the icon on the BufferedImage.  
            icon_in.paintIcon(null,bImage.getGraphics(),0,0); 
            return bImage;
        }
     
    }
    Images attachées Images attachées     
    S'il n'y a pas de solutions, il n'y a pas de problème.
      0  0

  7. #47
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Voici longtemps après les encrypteurs que j'ai posté deux streams sécrurisés de cryptage en RSA (en réalité en AES, voir mes posts précédents pour en connaître la raison). Ces streams permettent de lire / écrire n'importe quel type d'objet implémentant Serializable ou type primitif.

    Classe RSASecureObjectOutputStream :

    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
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
     
    /*
     * SecureObjectOutputStream.java
     *
     * Created on 5 mai 2007, 11:04
     *
     */
     
    package security;
     
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutput;
    import java.io.ObjectOutputStream;
    import java.io.ObjectStreamConstants;
    import java.io.OutputStream;
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.CipherOutputStream;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
     
    /**
     * This class models a SecureObjectOutputStream object that will be able to
     * write datas and object by crypting them with the RSA algotithm.<br>
     * Actually they are written with the AES algorithm, and the AES secret key
     * is crypted with the RSA, so the crypting is as secured as if it was a RSA
     * encryption, but is quite faster because of the symetry of the AES algorithm.
     * @author Absil Romain
     */
    public class RSASecureObjectOutputStream extends OutputStream 
            implements ObjectOutput, ObjectStreamConstants
    {
        private SecretKey secretKey;
        private Key publicKey;
        private ObjectOutputStream out;
        private String cryptedAESKey;
        private String outputFileName;
     
        /**
         * Constructs a new instance of RSASecureObjectOutputStream with the 
         * specified output file to write the datas in, the public RSA key to 
         * encrypt the AES secret key wich will really encrypt the file.
         * @param outputFileName the name of the input file to write the datas in.
         * @param publicRSAKeyInputFileName the name of the file containing the RSA
         * public key.
         * @param cryptedAESKey the name of the file to write the AES secret key in.
         * @throws java.io.FileNotFoundException if one of the input files is 
         * not found.
         * @throws java.io.IOException if an error occurs during writing datas.
         * @throws java.lang.ClassNotFoundException if the class of one of the keys
         * is not suitable
         * @throws java.security.InvalidKeyException if the given key is invalid.
         */
        public RSASecureObjectOutputStream(String outputFileName, 
                String publicRSAKeyInputFileName, String cryptedAESKey)
            throws FileNotFoundException, IOException, ClassNotFoundException, 
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicRSAKeyInputFileName));
            this.publicKey = (Key)keyIn.readObject();
            keyIn.close();
     
            this.outputFileName = outputFileName;
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectOutputStream with the 
         * specified output file to write the datas in, the public RSA key to 
         * encrypt the AES secret key wich will really encrypt the file.
         * @param outputFile the input file to write the datas in.
         * @param publicRSAKeyInputFileName the name of the file containing the RSA
         * public key.
         * @param cryptedAESKey the name of the file to write the AES secret key in.
         * @throws java.io.IOException if an error occurs during writing datas.
         * @throws java.lang.ClassNotFoundException if the class of one of the keys
         * is not suitable
         * @throws java.security.InvalidKeyException if the given key is invalid.
         */
        public RSASecureObjectOutputStream(File outputFile, 
                String publicRSAKeyInputFileName, String cryptedAESKey) 
                throws InvalidKeyException, IOException, ClassNotFoundException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicRSAKeyInputFileName));
            this.publicKey = (Key)keyIn.readObject();
            keyIn.close();
     
            this.outputFileName = outputFile.getAbsolutePath();
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectOutputStream with the 
         * specified output file to write the datas in, the public RSA key to 
         * encrypt the AES secret key wich will really encrypt the file.
         * @param outputFile the input file to write the datas in.
         * @param publicRSAKeyInputFile the file containing the RSA
         * public key.
         * @param cryptedAESKey the name of the the file to write the AES secret key in.
         * @throws java.io.IOException if an error occurs during writing datas.
         * @throws java.lang.ClassNotFoundException if the class of one of the keys
         * is not suitable
         * @throws java.security.InvalidKeyException if the given key is invalid.
         */
        public RSASecureObjectOutputStream(File outputFile, 
                File publicRSAKeyInputFile, String cryptedAESKey) 
                throws InvalidKeyException, IOException, ClassNotFoundException 
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicRSAKeyInputFile.getAbsolutePath()));
            this.publicKey = (Key)keyIn.readObject();
            keyIn.close();
     
            this.outputFileName = outputFile.getAbsolutePath();
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectOutputStream with the 
         * specified output file to write the datas in, the public RSA key to 
         * encrypt the AES secret key wich will really encrypt the file.
         * @param outputFileName the name of the input file to write the datas in.
         * @param publicKey the RSA public key.
         * @param cryptedAESKey the name of the file to write the AES secret key in.
         * @throws java.security.InvalidKeyException if the given key is invalid.
         * @throws java.io.IOException if an error occurs during writing datas.
         */
        public RSASecureObjectOutputStream(String outputFileName, Key publicKey, 
                String cryptedAESKey) throws InvalidKeyException, IOException
        {
            this.outputFileName = outputFileName;
            this.publicKey = publicKey;
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectOutputStream with the 
         * specified output file to write the datas in, the public RSA key to 
         * encrypt the AES secret key wich will really encrypt the file.
         * 
         * @param outputFile the input file to write the datas in.
         * @param publicKey the RSA public key.
         * @param cryptedAESKey the name of the file to write the AES secret key in.
         * @throws java.security.InvalidKeyException if the given key is invalid.
         * @throws java.io.IOException if an error occurs during writing datas.
         */
        public RSASecureObjectOutputStream(File outputFile, Key publicKey, 
                String cryptedAESKey) throws InvalidKeyException, IOException
        {
            this.outputFileName = outputFile.getAbsolutePath();
            this.publicKey = publicKey;
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        //initializes the stream and all its variables
        private void initialize() throws InvalidKeyException, IOException
        {
            KeyGenerator keygen = null;
            Cipher cipher = null;
     
            try
            {
                keygen = KeyGenerator.getInstance("AES");
                cipher = Cipher.getInstance("AES");
            } 
            catch (Exception ex)//jamais lancé
            {}
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            this.secretKey = keygen.generateKey();
     
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
     
            this.out = new ObjectOutputStream(
                    new CipherOutputStream(
                        new FileOutputStream(outputFileName), cipher));
     
            //write the AES secret key
            byte[] wrappedKey = null;
            try
            {
                cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.WRAP_MODE, publicKey);
                wrappedKey = cipher.wrap(secretKey);
            }
            catch(Exception e)//jamais lancé
            {}
            DataOutputStream out = new DataOutputStream(new FileOutputStream(cryptedAESKey));
            out.write(wrappedKey);
            out.close();
        }
     
        /**
         * Writes a byte to the output file.
         * @param b the byte to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void write(int b) throws IOException
        {
            out.write(b);
        }
     
        /**
         * Writes a byte buffer to the output file.
         * @param buffer the byte buffer to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void write(byte[] buffer) throws IOException
        {
            out.write(buffer);
        }
     
        /**
         * Writes a byte buffer from the starting offet and the given length to 
         * the output file.
         * @param buffer the byte buffer to write to the output file.
         * @param offset the starting offset of the byte buffer to write.
         * @param length the length of the byte buffer to write.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void write(byte[] buffer, int offset, int length) throws IOException
        {
            out.write(buffer, offset, length);
        }
     
        /**
         * Writes a boolean to the output file.
         * @param b the boolean to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeBoolean(boolean b) throws IOException
        {
            out.writeBoolean(b);
        }
     
        /**
         * Writes a 8 bit byte to the output file.
         * @param b the 8 bit byte to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeByte(int b) throws IOException
        {
            out.writeByte(b);
        }
     
        /**
         * Writes a String as a sequence of bytes to the output file.
         * @param str the String to write as a sequence of bytes to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeBytes(String str) throws IOException
        {
            out.writeBytes(str);
        }
     
        /**
         * Writes a 16 bit char to the output file.
         * @param val the 16 bit char to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeChar(int val) throws IOException
        {
            out.writeChar(val);
        }
     
        /**
         * Writes a String as a sequence of chars to the output file.
         * @param str the String to write as a sequence of chars to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeChars(String str) throws IOException
        {
            out.writeChars(str);
        }
     
        /**
         * Writes a 64 bit double to the output file.
         * @param d the 64 bit double to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeDouble(double d) throws IOException
        {
            out.writeDouble(d);
        }
     
        /**
         * Writes a 32 bit float to the output file.
         * @param f the 32 bit float to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeFloat(float f) throws IOException
        {
            out.writeFloat(f);
        }
     
        /**
         * Writes a 32 bits int to the output file.
         * @param n the 32 bit int to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeInt(int n) throws IOException
        {
            out.writeInt(n);
        }
     
        /**
         * Writes a 64 bit long to the output file.
         * @param l the 64 bit long to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeLong(long l) throws IOException
        {
            out.writeLong(l);
        }
     
        /**
         * Writes a 16 bit short to the output file.
         * @param s the 16 bit short to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeShort(int s) throws IOException
        {
            out.writeShort(s);
        }
     
        /**
         * Writes an object to the output file.
         * @param o the object to write to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeObject(Object o) throws IOException
        {
            out.writeObject(o);
        }
     
        /**
         * Primitive data write of this String in modified UTF-8  format.
         * @param str the String to write in modified UTF-8  format to the output file.
         * @throws java.io.IOException if an error occurs during encrypting datas.
         */
        public void writeUTF(String str) throws IOException
        {
            out.writeUTF(str);
        }
     
        /**
         * Closes the stream.
         * @throws java.io.IOException if an error occurs during closing the output
         * file.
         */
        public void close() throws IOException
        {
            out.close();
        }
     
        /**
         * Flushes the stream
         * @throws java.io.IOException if an error occurs during flushing the
         * stream.
         */
        public void flush() throws IOException
        {
            out.flush();
        }
    }
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  8. #48
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Et voici maintenant le stream permettant de lire les donnée scryptées avec RSASerureObjectOutputStream.

    Classe RSASecureObjectInputStream :
    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
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
     
    /*
     * SecureObjectInputStream.java
     *
     * Created on 5 mai 2007, 11:04
     *
     */
     
    package security;
     
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInput;
    import java.io.ObjectInputStream;
    import java.io.ObjectStreamConstants;
    import java.security.InvalidKeyException;
    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.CipherInputStream;
    import javax.crypto.SecretKey;
     
    /**
     * This class models a SecureObjectInputStream object that will be able to
     * read datas and object by decrypting them with the RSA algotithm.<br>
     * Actually they are read with the AES algorithm, and the AES secret key
     * is decrypted with the RSA, so the decrypting is as secured as if it was a RSA
     * decryption, but is quite faster because of the symetry of the AES algorithm.
     * @author Absil Romain
     */
    public class RSASecureObjectInputStream extends InputStream 
            implements ObjectInput, ObjectStreamConstants
    {
        private SecretKey secretKey;
        private Key privateKey;
        private ObjectInputStream in;
        private String inputFileName;
        private String cryptedAESKey;
     
        /**
         * Constructs a new instance of RSASecureObjectInputStream with the 
         * specified file to read the datas from, the private RSA key to decrypt 
         * the AES secret key wich will really decrypt the file.
         * @param privateRSAKeyInputFileName the name of the file containing the
         * private RSA key.
         * @param cryptedAESKey the name of the file containing the crypted AES
         * key.
         * @param inputFileName the name of the input file to decrypt.
         * @throws java.io.FileNotFoundException if one of the input files is not found.
         * @throws java.io.IOException if an I/O error occurs during reading 
         * the input files.
         * @throws java.security.InvalidKeyException if the given key is invalid.
         * @throws java.lang.ClassNotFoundException if the class of the key is not
         * suitable.
         */
        public RSASecureObjectInputStream(String inputFileName, 
                String privateRSAKeyInputFileName, String cryptedAESKey) 
                    throws FileNotFoundException, IOException, InvalidKeyException,
                        ClassNotFoundException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(privateRSAKeyInputFileName));
            this.privateKey = (Key)keyIn.readObject();
            keyIn.close();
     
            this.inputFileName = inputFileName;
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectInputStream with the 
         * specified input file to read the datas from, the private RSA key to 
         * decrypt the AES secret key wich will really decrypt the file.
         * @param cryptedAESKey the name of the file containing the crypted AES
         * key.
         * @param inputFile the input file to read the datas from.
         * @param privateRSAKeyInputFileName the name of the file containing the RSA
         * private key.
         * @throws java.io.IOException if an I/O error occurs during reading 
         * the input files.
         * @throws java.security.InvalidKeyException if the given key is invalid.
         * @throws java.lang.ClassNotFoundException if the class of the key is not
         * suitable.
         */
        public RSASecureObjectInputStream(File inputFile, 
                String privateRSAKeyInputFileName, String cryptedAESKey) 
                throws InvalidKeyException, IOException, ClassNotFoundException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(privateRSAKeyInputFileName));
            this.privateKey = (Key)keyIn.readObject();
            keyIn.close();
     
            this.inputFileName = inputFile.getAbsolutePath();
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectInputStream with the 
         * specified input file to read the datas from, the private RSA key to 
         * decrypt the AES secret key wich will really decrypt the file.
         * @param cryptedAESKey the name of the file containing the crypted AES
         * key.
         * @param inputFile the input file to read the datas from.
         * @param privateRSAKeyInputFile the file containing the RSA private key.
         * @throws java.io.IOException if an I/O error occurs during reading 
         * the input files.
         * @throws java.security.InvalidKeyException if the given key is invalid.
         * @throws java.lang.ClassNotFoundException if the class of the key is not
         * suitable.
         */
        public RSASecureObjectInputStream(File inputFile, 
                File privateRSAKeyInputFile, String cryptedAESKey) 
                throws InvalidKeyException, IOException, ClassNotFoundException 
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(privateRSAKeyInputFile.getAbsolutePath()));
            this.privateKey = (Key)keyIn.readObject();
            keyIn.close();
     
            this.inputFileName = inputFile.getAbsolutePath();
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectInputStream with the 
         * specified input file to read the datas from, the private RSA key to 
         * decrypt the AES secret key wich will really decrypt the file.
         * @param cryptedAESKey the name of the file containing the crypted AES
         * key.
         * @param inputFileName the name of the input file to read the datas from.
         * @param privateKey the key the RSA private key.
         * @throws java.io.IOException if an I/O error occurs during reading 
         * the input files.
         * @throws java.security.InvalidKeyException if the given key is invalid.
         */
        public RSASecureObjectInputStream(String inputFileName, Key privateKey, 
                String cryptedAESKey) throws InvalidKeyException, IOException
        {
            this.inputFileName = inputFileName;
            this.privateKey = privateKey;
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        /**
         * Constructs a new instance of RSASecureObjectInputStream with the 
         * specified input file to read the datas from, the private RSA key to 
         * decrypt the AES secret key wich will really decrypt the file.
         * @param cryptedAESKey the name of the file containing the crypted AES
         * key.
         * @param inputFile the input file to read the datas from.
         * @param privateKey the key the RSA private key.
         * @throws java.io.IOException if an I/O error occurs during reading 
         * the input files.
         * @throws java.security.InvalidKeyException if the given key is invalid.
         */
        public RSASecureObjectInputStream(File inputFile, Key privateKey, 
                String cryptedAESKey) throws InvalidKeyException, IOException
        {
            this.inputFileName = inputFile.getAbsolutePath();
            this.privateKey = privateKey;
            this.cryptedAESKey = cryptedAESKey;
     
            initialize();
        }
     
        //initializes the stream and all its variables
        private void initialize() throws FileNotFoundException, IOException
        {
            DataInputStream in = new DataInputStream(new FileInputStream(cryptedAESKey));
            File f = new File(cryptedAESKey);
            int length = (int)f.length();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);
     
            try
            {
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.UNWRAP_MODE, privateKey);            
                this.secretKey = (SecretKey)cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
     
                cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.DECRYPT_MODE, secretKey);
                this.in = new ObjectInputStream(new CipherInputStream(new FileInputStream(inputFileName), cipher));
            }
            catch(Exception e)
            {}
        }
     
        /**
         * Reads a byte from the input file.
         * @return the read byte.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public int read() throws IOException
        {
            return in.read();
        }
     
        /**
         * Reads bytes in the given byte buffer from the starting offset and the
         * given length from the input file..
         * @param buffer the byte buffer to read the bytes in.
         * @param offset the starting offset of the datas.
         * @param length the length of the bytes to read.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         * @return the length of the read bytes, -1 if the end of the file has
         * already been reached.
         */
        public int read(byte[] buffer, int offset, int length) throws IOException
        {
            return in.read(buffer, offset, length);
        }
     
        /**
         * Reads a boolean from the input file.
         * @return the read boolean.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public boolean readBoolean() throws IOException
        {
            return in.readBoolean();
        }
     
        /**
         * Reads a 8 bit byte from the input file.
         * @return the read 8 bit byte.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public byte readByte() throws IOException
        {
            return in.readByte();
        }
     
        /**
         * Reads a 16 bit char from the input file.
         * @return the read 16 bit char.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public char readChar() throws IOException
        {
            return in.readChar();
        }
     
        /**
         * Reads a 64 bit double from the input file.
         * @return the read 64 bit double.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public double readDouble() throws IOException
        {
            return in.readDouble();
        }
     
        /**
         * Reads a 32 bit float from the input file.
         * @return the read 32 bit float.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public float readFloat() throws IOException
        {
            return in.readFloat();
        }
     
        /**
         * Reads a byte buffer from the input file, blocking until all bytes are read.
         * @param buffer the buffer to read the bytes in.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public void readFully(byte[] buffer) throws IOException
        {
            in.readFully(buffer);
        }
     
        /**
         * Reads a byte buffer from the given starting offset and length from the 
         * input file, blocking until all bytes are read.
         * @param buffer the buffer to read.
         * @param offset the starting offset of the buffer to read.
         * @param length the length of the buffer to read.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public void readFully(byte[] buffer, int offset, int length) 
            throws IOException
        {
            in.readFully(buffer, offset, length);
        }
     
        /**
         * Reads a 32 bits int from the input file.
         * @return the read 32 bit int.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public int readInt() throws IOException
        {
            return in.readInt();
        }
     
        /**
         * Reads a 64 bit long from the input file.
         * @return the read 34 bit long.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public long readLong() throws IOException
        {
            return in.readLong();
        }
     
        /**
         * Reads a line from the input file.
         * @return the read line
         * @deprecated This method does not properly convert bytes to characters. 
         * See DataInputStream for the details and alternatives.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public String readLine() throws IOException
        {
            return in.readLine();
        }
     
        /**
         * Reads an object from the input file.
         * @return the read object.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         * @throws java.lang.ClassNotFoundException if the class of the read
         * object is unknown.
         */
        public Object readObject() throws IOException, ClassNotFoundException
        {
            return in.readObject();
        }
     
        /**
         * Reads a 16 bit short from the input file.
         * @return the read 16 bit short.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public short readShort() throws IOException
        {
            return in.readShort();
        }
     
        /**
         * Reads an unsigned 8 bit byte from the input file.
         * @return the read unsigned 8 bit byte.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public int readUnsignedByte() throws IOException
        {
            return in.readUnsignedByte();
        }
     
        /**
         * Reads an unsigned 16 bit short from the input file.
         * @return the read unsigned 16 bit short.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public int readUnsignedShort() throws IOException
        {
            return in.readUnsignedShort();
        }
     
        /**
         * Reads a String in modified UTF-8  format from the input file.
         * @return the read String in modified UTF-8  format.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public String readUTF() throws IOException
        {
            return in.readUTF();
        }
     
        /**
         * Skip bytes, blocking until all bytes are read.
         * @return the length of the skypped bytes, -1 if the end of the file
         * has already been reached.
         * @param length the length of the bytes to skip.
         * @throws java.io.IOException if an I/O error occurs during reading the
         * input file.
         */
        public int skipBytes(int length) throws IOException
        {
            return in.skipBytes(length);
        }
     
        /**
         * Closes the stream.
         * @throws java.io.IOException if an I/O error occurs during closing the
         * input file.
         */
        public void close() throws IOException
        {
            in.close();
        }
    }
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  9. #49
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Rien à voir avec le cryptage maintenant, voici une petite classe écouteur à ajouter à tout bouton de type "Parcourir" pour displayer un JFileChooser et récupérer le path choisi. C'est plus élaboré que ça en a l'air

    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
     
    /*
     * BrowseListener.java
     *
     * Created on 28 avril 2007, 12:55
     *
     */
     
    package graphics;
     
    import java.awt.Component;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import javax.swing.text.JTextComponent;
     
    /**
     * This class models a BrowseListener object that can be added to a browse 
     * component, such as a button "Browse".
     * @author Absil Romain
     */
    public class BrowseListener implements ActionListener
    {
        private String selectMsg;
        private String errorMsg;
        private JTextComponent field;
        private Component parent;
        private String desc;
        private String[] exts;
        private boolean exists;
        private String path;
     
        /**
         * Construcs a new BrowsLisetner with a specified message as selection
         * message, a message in case of error, a parameter if the file choosen
         * by the displayed {@link javax.swing.JFileChooser} must exist, a text
         * component in wich the result of browsing must be displayed, a parent
         * compoenent for the displayed {@link javax.swing.JFileChooser}, a 
         * description of the accepted files and extensions of the accepted files.
         * @param selectMsg the selection message.
         * @param errorMsg the error message.
         * @param exists the existance parameter.
         * @param field the text component on wich you want to display the result.
         * If you don't, just give a null parameter.
         * @param parent the parent component for the {@link javax.swing.JFileChooser}.
         * @param desc the description of the accepted files.
         * @param exts the extension of the accepted files.
         **/
        public BrowseListener(String selectMsg, String errorMsg, 
                boolean exists, JTextComponent field, Component parent, String desc, 
                    String ... exts)
        {
            this.desc = desc;
            this.errorMsg = errorMsg;
            this.exts = exts;
            this.field = field;
            this.exists = exists;
            this.parent = parent;
            this.selectMsg = selectMsg;
        }
     
        /**
         * This method is invoked at any time an event is fired by the component on
         * wich the listener has been added.
         * @param e the fired event.
         **/
        public void actionPerformed(ActionEvent e)
        {
            JFileChooser chooser = new JFileChooser();
            JFileFilter filter = new JFileFilter(desc,exts);
            chooser.setFileFilter(filter);
            String title = selectMsg;
            chooser.setDialogTitle(title);
            int returnval = chooser.showOpenDialog(parent);
            if(returnval == chooser.APPROVE_OPTION)
            {
                String fileName = chooser.getCurrentDirectory()
                .getAbsolutePath() + File.separatorChar +
                        chooser.getSelectedFile().getName();
                File file = new File(fileName);
     
                if(!exists || (exists && file.exists()))
                {
                    path = fileName;
                    if(field != null)
                        field.setText(fileName);
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, errorMsg, "Erreur",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
     
        /**
         * Returns the path displeyed by the text component.
         **/
        public String getPath()
        {
            return path;
        }
    }
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  10. #50
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Oups, voici la classe JFileFilter utilisée pour BrowsListener, je m'en suis inspiré d'un post de ce site je pense, mais je ne saurai plus me rapeller de où...

    Classe JFileFilter :
    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
     
    package graphics;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    import javax.swing.filechooser.FileFilter;
     
    /**
     * This class models a simple file filter with a description for accepted files
     * and their extensions.
     **/
    public class JFileFilter extends FileFilter
    {
     
        private String description;
        private ArrayList<String> acceptedExtensions = new ArrayList<String>();
     
        /**
         * Creates a new JFileFilter object with the specified description for 
         * accepted files and their extensions.
         * @param description the description of the accepted files.
         * @param extensions the extensions of the accepted files.
         **/
        public JFileFilter(String description, String ... extensions)
        {
            if(description == null || extensions.length == 0)
                throw new NullPointerException();
     
            this.description = description; 
            for(String extension : extensions)
                acceptedExtensions.add(extension);
        } 
     
        /**
         * Adds an extensions to the accepted extensions of the file filter.
         * @param extension the extension to ad.
         **/
        public void addExtension(String extension)
        {
            acceptedExtensions.add(extension);
        }
     
        /**
         * Removes an extension from the accepted extensions of the file filter.
         * @param extension the extension to remove.
         **/
        public void removeExtension(String extension)
        {
           acceptedExtensions.remove(extension);
        }
     
        /**
         * Returns true if the given file is accepted by the file filter, returns
         * false otherwise.
         * @return true if the given file is accepted by the file filter, returns
         * false otherwise.
         **/
        public boolean accept(File file)
        {
            String nomFichier = file.getName().toLowerCase();
            if(file.isDirectory())
                return true;
            else
                for(int i = 0; i < acceptedExtensions.size();i++)
                    if(nomFichier.endsWith(acceptedExtensions.get(i)))
                        return true;
            return false;
     
        } 
     
        /** 
         * Returns the description of the accepted files.
         * @return the description of the accepted files.
         */ 
        public String getDescription()
        {
            String rep = description + " ( ." + acceptedExtensions.get(0);
            for(int i = 1; i < acceptedExtensions.size(); i++)
                rep += ", ."+ acceptedExtensions.get(i);
            return rep + " )";
        }
     
    }
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  11. #51
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Voici une correction des classes fournissant les condensés de hachage que j'avais postée précédement dans ce topic.
    Un grand merci à le y@ms pour sa grande contribution à cette classe.

    [EDIT] Dernière mise à jour de la classe effectuée (et en ligne) le 13/09 [/EDIT]

    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
     
    /*
     * Hasher.java
     *
     * Created on 13 mai 2007, 16:41
     *
     */
     
    package org.cosmopol.security;
     
    import java.io.BufferedInputStream; 
    import java.io.File; 
    import java.io.FileInputStream; 
    import java.io.FileNotFoundException;
    import java.io.IOException; 
    import java.io.InputStream; 
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.charset.Charset;
    import java.security.MessageDigest; 
    import java.security.NoSuchAlgorithmException; 
    import java.util.Arrays;
     
    /**
     * This class provides methods for message hashing with hash algorithms
     * such as SHA-1, MD5 and so on.
     * @author Romain Absil, Yann D'Isanto 
     */ 
     
    public class Hasher 
    { 
        private MessageDigest algorithm;
     
        /** 
         * SHA-1 algorithm. 
         **/  
        public static final String SHA1 = "SHA-1"; 
     
        /** 
         * SHA-256 algorithm. 
         **/ 
        public static final String SHA256 = "SHA-256";
     
        /**
         * SHA-384 algorithm. 
         **/  
        public static final String SHA384 = "SHA-384";
     
        /**
         * SHA-512 algorithm. 
         **/ 
        public static final String SHA512 = "SHA-512"; 
     
        /** 
         * MD2 algorithm. 
         **/  
        public static final String MD2 = "MD2"; 
     
        /** 
         * MD5 algorithm. 
         **/  
        public static final String MD5 = "MD5"; 
     
        /**
         * Creates a Hasher with a default algorithm. 
         * {@link org.umh.security.Hasher#SHA256}.
         **/
        public Hasher() 
        {  
            try 
            {  
                this.algorithm = MessageDigest.getInstance(SHA256); 
            } 
            catch (NoSuchAlgorithmException ex) //never thrown
            {
                ex.printStackTrace(); 
            }  
        }  
     
        /**
         * Create a Hasher that will uses the specified algorithm. 
         * @param algorithm the algorithm 
         */  
        public Hasher(MessageDigest algorithm) 
        {  
            this.algorithm = algorithm; 
        }  
     
        /**
         * 
         * Create a Hasher that will uses the specified algorithm.
         * @param algorithm the algorithm to use.
         * @throws java.security.NoSuchAlgorithmException if the specified algorithm is not a valid algorithm for message hashing.
         */  
        public Hasher(String algorithm) throws NoSuchAlgorithmException 
        {  
            this.algorithm = MessageDigest.getInstance(algorithm); 
        }  
     
        /** 
         * Set the algorithm of the hasher.
         * @param algorithm the algorithm to set.
         */  
        public void setAlgorithm(MessageDigest algorithm) 
        {  
            this.algorithm = algorithm; 
        }
     
        /**
         * Set the algorithm of the hasher.
         * @param algorithm the algorithm to set.
         * @throws java.security.NoSuchAlgorithmException if the specified algorithm is not a valid algorithm for message hashing.
         */  
        public void setAlgorithm(String algorithm) throws NoSuchAlgorithmException 
        {  
            setAlgorithm(MessageDigest.getInstance(algorithm)); 
        }  
     
        /** 
         * Returns the algorithm. 
         * @return the algorithm 
         */      
        public MessageDigest getAlgorithm() 
        {  
            return algorithm; 
        } 
     
        /**
         * Hashes the file denoted by the specified location to a bytes array.
         * @param pathname file location. 
         * @return the hash as a bytes array. 
         * @throws java.io.FileNotFoundException if the file to hash doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * to hash.
         */ 
        public byte[] hash(String pathname) 
            throws FileNotFoundException, IOException 
        { 
            return hash(new File(pathname));
        } 
     
        /** 
         * Hashes the specified file to a bytes array.
         * @param file the file to hash. 
         * @return the hash as a bytes array .
         * @throws java.io.FileNotFoundException if the file to hash doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * to hash.
         */  
        public byte[] hash(File file) throws FileNotFoundException, IOException 
        {  
            FileInputStream fis = new FileInputStream(file); 
            byte[] hash = null; 
            try 
            {  
                hash = hash(fis); 
            } 
            finally 
            {  
                fis.close(); 
            }  
            return hash; 
        }  
     
        /** 
         * Hashes the specified input stream. 
         * @param is the input stream to hash 
         * @return the hash as a bytes array .
         * @throws java.io.IOException if an error occurs during reading the stream 
         * to hash.
         */  
        public byte[] hash(InputStream is) throws IOException 
        {  
            BufferedInputStream bis = new BufferedInputStream(is);
            algorithm.reset(); 
            byte[] data = new byte[2048]; 
            int nbRead = 0; 
            while((nbRead = bis.read(data)) > 0) 
            {  
                algorithm.update(data, 0, nbRead);
            }  
            bis.close();
            bis = null;
            return algorithm.digest();
        }  
     
        /**
         * Hashes the specified datas under bytes array format.
         * @param datas the datas to hash.
         * @return the hash under bytes array format.
         **/
        public byte[] hash(byte[] datas)
        {
            algorithm.reset();
            algorithm.update(datas);
            return algorithm.digest();
        }
     
        /**
         * Hashes the specified chars array.
         * @param chars the chars to hash.
         * @return the hash under bytes array format.
         **/
        public byte[] hash(char[] chars)
        {
            byte[] bytes = toByteArray(chars);
            return hash(bytes);
        }
     
        /** 
         * Hashes the file denoted by the specified location to a String.
         * @param pathname file location. 
         * @return the hash as a String.
         * @throws java.io.FileNotFoundException if the file to hash doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * to hash.
         */  
        public String hashToString(String pathname) 
            throws FileNotFoundException, IOException 
        { 
            return buildHexaString(hash(pathname)); 
        }  
     
        /** 
         * Hashes the specified file to a String.
         * @param file the file to hash. 
         * @return the hash as a String.
         * @throws java.io.FileNotFoundException if the file to hash doesn't exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * to hash. 
         */  
        public String hashToString(File file)
            throws FileNotFoundException, IOException 
        {  
            return buildHexaString(hash(file));
        }  
     
        /** 
         * Hashes the specified input stream to a String.
         * @param is the input stream to hash. 
         * @return the hash as a String.
         * @throws java.io.IOException if an error occurs during reading the file 
         * to hash. 
         */  
        public String hashToString(InputStream is) 
            throws IOException 
        {  
            return buildHexaString(hash(is)); 
        }  
     
        /**
         * Hashes the specified datas under bytes array format and returns the 
         * hash as an hexadecimal String.
         * @param datas the datas to hash.
         * @return the hash as an hexadecimal String.
         **/
        public String hashToString(byte[] datas)
        {
            return buildHexaString(hash(datas));
        }
     
        /**
         * Hashes the specified chars array and returns the hash as an hexadecimal
         * String.
         * @param chars the chars to hash.
         * @return the hash as an hexadecimal String.
         **/
        public String hashToString(char[] chars)
        {
            return buildHexaString(hash(chars));
        }
     
        /** 
         * Returns the specified bytes array as an hexadecimal String. 
         * @param hash the datas as a bytes array.
         * @return the hash as an hexadecimal String.
         */  
        public String buildHexaString(byte[] hash)
        {  
            StringBuilder sb = new StringBuilder(); 
            for (int i = 0; i < hash.length; i++) 
            {  
                int v = hash[i] & 0xFF; 
                if(v < 16) 
                    sb.append("0"); 
                sb.append(Integer.toString(v, 16).toUpperCase() + " "); 
            }  
            return sb.toString(); 
        }  
     
        /**
         * Converts the specified chars array to a bytes array using the default
         * charset.
         * @param chars the chars to convert.
         * @return the specified chars converted to a bytes array.
         **/
        public static byte[] toByteArray(char[] chars)
        {
            return toByteArray(chars, Charset.defaultCharset());
        }
     
        /**
         * Converts the specified chars array to a bytes array using the charset
         * of the specified name.
         * @param chars the chars to convert.
         * @param charsetName the name of the charset used for chars encoding.
         * @return the specified chars converted to a bytes array.
         **/
        public static byte[] toByteArray(char[] chars, String charsetName)
        {
            Charset cs = Charset.forName(charsetName);
            return toByteArray(chars, cs);
        }
     
        /**
         * Converts the specified chars array to a bytes array using the specified
         * charset.
         * @param chars the chars to convert.
         * @param charset the charset used for chars encoding.
         * @return the specified chars converted to a bytes array.
         **/
        public static byte[] toByteArray(char[] chars, Charset charset)
        {
            CharBuffer cb = CharBuffer.wrap(chars);
            ByteBuffer bb = charset.encode(cb);
            byte[] bytes = bb.array();
            byte[] result = Arrays.copyOf(bytes, bb.limit());
            Arrays.fill(bytes, (byte)0);
            return result;
        }
    }
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  12. #52
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Voici également un lein vers une petite librairie d'analyse numérique que j'ai développée et postée sur un topic à part.
    Les domaines explorés sont :
    - Recherche de racine
    - Résolution de systèmes linéaires
    - Interpolation
    - Intégration

    http://www.developpez.net/forums/sho...d.php?t=335525
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  13. #53
    Membre expert
    Avatar de ®om
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    2 815
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 2 815
    Points : 3 080
    Points
    3 080
    Par défaut
    Voici une enum qui représente les languages de l'iso 639.2.
    Plutôt qu'utiliser des String non vérifiés...
    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
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953
    954
    955
    956
    957
    958
    959
    960
    961
    962
    963
    964
    965
    966
    967
    968
    969
    970
    971
    972
    973
    974
    975
    976
    977
    978
    979
    980
    981
    982
    983
    984
    985
    986
    987
    988
    989
    990
    991
    992
    993
    994
    995
    996
    997
    998
    999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
    1274
    1275
    1276
    1277
    1278
    1279
    1280
    1281
    1282
    1283
    1284
    1285
    1286
    1287
    1288
    1289
    1290
    1291
    1292
    1293
    1294
    1295
    1296
    1297
    1298
    1299
    1300
    1301
    1302
    1303
    1304
    1305
    1306
    1307
    1308
    1309
    1310
    1311
    1312
    1313
    1314
    1315
    1316
    1317
    1318
    1319
    1320
    1321
    1322
    1323
    1324
    1325
    1326
    1327
    1328
    1329
    1330
    1331
    1332
    1333
    1334
    1335
    1336
    1337
    1338
    1339
    1340
    1341
    1342
    1343
    1344
    1345
    1346
    1347
    1348
    1349
    1350
    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    1375
    1376
    1377
    1378
    1379
    1380
    1381
    1382
    1383
    1384
    1385
    1386
    1387
    1388
    1389
    1390
    1391
    1392
    1393
    1394
    1395
    1396
    1397
    1398
    1399
    1400
    1401
    1402
    1403
    1404
    1405
    1406
    1407
    1408
    1409
    1410
    1411
    1412
    1413
    1414
    1415
    1416
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    /**
     * Languages from ISO 639.2.
     * 
     * @author <a href="mailto:rom1v@yahoo.fr">Romain Vimont</a> (rom1v)
     */
    public enum Language {
     
    	/** Afar */
    	AAR("Afar"),
     
    	/** Abkhazian */
    	ABK("Abkhazian"),
     
    	/** Achinese */
    	ACE("Achinese"),
     
    	/** Acoli */
    	ACH("Acoli"),
     
    	/** Adangme */
    	ADA("Adangme"),
     
    	/** Adyghe; Adygei */
    	ADY("Adyghe; Adygei"),
     
    	/** Afro-Asiatic (Other) */
    	AFA("Afro-Asiatic (Other)"),
     
    	/** Afrihili */
    	AFH("Afrihili"),
     
    	/** Afrikaans */
    	AFR("Afrikaans"),
     
    	/** Ainu */
    	AIN("Ainu"),
     
    	/** Akan */
    	AKA("Akan"),
     
    	/** Akkadian */
    	AKK("Akkadian"),
     
    	/** Albanian */
    	ALB("Albanian"),
     
    	/** Aleut */
    	ALE("Aleut"),
     
    	/** Algonquian languages */
    	ALG("Algonquian languages"),
     
    	/** Southern Altai */
    	ALT("Southern Altai"),
     
    	/** Amharic */
    	AMH("Amharic"),
     
    	/** English, Old (ca.450-1100) */
    	ANG("English, Old (ca.450-1100)"),
     
    	/** Angika */
    	ANP("Angika"),
     
    	/** Apache languages */
    	APA("Apache languages"),
     
    	/** Arabic */
    	ARA("Arabic"),
     
    	/** Aramaic */
    	ARC("Aramaic"),
     
    	/** Aragonese */
    	ARG("Aragonese"),
     
    	/** Armenian */
    	ARM("Armenian"),
     
    	/** Mapudungun; Mapuche */
    	ARN("Mapudungun; Mapuche"),
     
    	/** Arapaho */
    	ARP("Arapaho"),
     
    	/** Artificial (Other) */
    	ART("Artificial (Other)"),
     
    	/** Arawak */
    	ARW("Arawak"),
     
    	/** Assamese */
    	ASM("Assamese"),
     
    	/** Asturian; Bable */
    	AST("Asturian; Bable"),
     
    	/** Athapascan languages */
    	ATH("Athapascan languages"),
     
    	/** Australian languages */
    	AUS("Australian languages"),
     
    	/** Avaric */
    	AVA("Avaric"),
     
    	/** Avestan */
    	AVE("Avestan"),
     
    	/** Awadhi */
    	AWA("Awadhi"),
     
    	/** Aymara */
    	AYM("Aymara"),
     
    	/** Azerbaijani */
    	AZE("Azerbaijani"),
     
    	/** Banda languages */
    	BAD("Banda languages"),
     
    	/** Bamileke languages */
    	BAI("Bamileke languages"),
     
    	/** Bashkir */
    	BAK("Bashkir"),
     
    	/** Baluchi */
    	BAL("Baluchi"),
     
    	/** Bambara */
    	BAM("Bambara"),
     
    	/** Balinese */
    	BAN("Balinese"),
     
    	/** Basque */
    	BAQ("Basque"),
     
    	/** Basa */
    	BAS("Basa"),
     
    	/** Baltic (Other) */
    	BAT("Baltic (Other)"),
     
    	/** Beja */
    	BEJ("Beja"),
     
    	/** Belarusian */
    	BEL("Belarusian"),
     
    	/** Bemba */
    	BEM("Bemba"),
     
    	/** Bengali */
    	BEN("Bengali"),
     
    	/** Berber (Other) */
    	BER("Berber (Other)"),
     
    	/** Bhojpuri */
    	BHO("Bhojpuri"),
     
    	/** Bihari */
    	BIH("Bihari"),
     
    	/** Bikol */
    	BIK("Bikol"),
     
    	/** Bini; Edo */
    	BIN("Bini; Edo"),
     
    	/** Bislama */
    	BIS("Bislama"),
     
    	/** Siksika */
    	BLA("Siksika"),
     
    	/** Bantu (Other) */
    	BNT("Bantu (Other)"),
     
    	/** Bosnian */
    	BOS("Bosnian"),
     
    	/** Braj */
    	BRA("Braj"),
     
    	/** Breton */
    	BRE("Breton"),
     
    	/** Batak languages */
    	BTK("Batak languages"),
     
    	/** Buriat */
    	BUA("Buriat"),
     
    	/** Buginese */
    	BUG("Buginese"),
     
    	/** Bulgarian */
    	BUL("Bulgarian"),
     
    	/** Burmese */
    	BUR("Burmese"),
     
    	/** Blin; Bilin */
    	BYN("Blin; Bilin"),
     
    	/** Caddo */
    	CAD("Caddo"),
     
    	/** Central American Indian (Other) */
    	CAI("Central American Indian (Other)"),
     
    	/** Galibi Carib */
    	CAR("Galibi Carib"),
     
    	/** Catalan; Valencian */
    	CAT("Catalan; Valencian"),
     
    	/** Caucasian (Other) */
    	CAU("Caucasian (Other)"),
     
    	/** Cebuano */
    	CEB("Cebuano"),
     
    	/** Celtic (Other) */
    	CEL("Celtic (Other)"),
     
    	/** Chamorro */
    	CHA("Chamorro"),
     
    	/** Chibcha */
    	CHB("Chibcha"),
     
    	/** Chechen */
    	CHE("Chechen"),
     
    	/** Chagatai */
    	CHG("Chagatai"),
     
    	/** Chinese */
    	CHI("Chinese"),
     
    	/** Chuukese */
    	CHK("Chuukese"),
     
    	/** Mari */
    	CHM("Mari"),
     
    	/** Chinook jargon */
    	CHN("Chinook jargon"),
     
    	/** Choctaw */
    	CHO("Choctaw"),
     
    	/** Chipewyan */
    	CHP("Chipewyan"),
     
    	/** Cherokee */
    	CHR("Cherokee"),
     
    	/**
             * Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church
             * Slavonic
             */
    	CHU(
    			"Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"),
     
    	/** Chuvash */
    	CHV("Chuvash"),
     
    	/** Cheyenne */
    	CHY("Cheyenne"),
     
    	/** Chamic languages */
    	CMC("Chamic languages"),
     
    	/** Coptic */
    	COP("Coptic"),
     
    	/** Cornish */
    	COR("Cornish"),
     
    	/** Corsican */
    	COS("Corsican"),
     
    	/** Creoles and pidgins, English based (Other) */
    	CPE("Creoles and pidgins, English based (Other)"),
     
    	/** Creoles and pidgins, French-based (Other) */
    	CPF("Creoles and pidgins, French-based (Other)"),
     
    	/** Creoles and pidgins, Portuguese-based (Other) */
    	CPP("Creoles and pidgins, Portuguese-based (Other)"),
     
    	/** Cree */
    	CRE("Cree"),
     
    	/** Crimean Tatar; Crimean Turkish */
    	CRH("Crimean Tatar; Crimean Turkish"),
     
    	/** Creoles and pidgins (Other) */
    	CRP("Creoles and pidgins (Other)"),
     
    	/** Kashubian */
    	CSB("Kashubian"),
     
    	/** Cushitic (Other) */
    	CUS("Cushitic (Other)"),
     
    	/** Czech */
    	CZE("Czech"),
     
    	/** Dakota */
    	DAK("Dakota"),
     
    	/** Danish */
    	DAN("Danish"),
     
    	/** Dargwa */
    	DAR("Dargwa"),
     
    	/** Land Dayak languages */
    	DAY("Land Dayak languages"),
     
    	/** Delaware */
    	DEL("Delaware"),
     
    	/** Slave (Athapascan) */
    	DEN("Slave (Athapascan)"),
     
    	/** Dogrib */
    	DGR("Dogrib"),
     
    	/** Dinka */
    	DIN("Dinka"),
     
    	/** Divehi; Dhivehi; Maldivian */
    	DIV("Divehi; Dhivehi; Maldivian"),
     
    	/** Dogri */
    	DOI("Dogri"),
     
    	/** Dravidian (Other) */
    	DRA("Dravidian (Other)"),
     
    	/** Lower Sorbian */
    	DSB("Lower Sorbian"),
     
    	/** Duala */
    	DUA("Duala"),
     
    	/** Dutch, Middle (ca.1050-1350) */
    	DUM("Dutch, Middle (ca.1050-1350)"),
     
    	/** Dutch; Flemish */
    	DUT("Dutch; Flemish"),
     
    	/** Dyula */
    	DYU("Dyula"),
     
    	/** Dzongkha */
    	DZO("Dzongkha"),
     
    	/** Efik */
    	EFI("Efik"),
     
    	/** Egyptian (Ancient) */
    	EGY("Egyptian (Ancient)"),
     
    	/** Ekajuk */
    	EKA("Ekajuk"),
     
    	/** Elamite */
    	ELX("Elamite"),
     
    	/** English */
    	ENG("English"),
     
    	/** English, Middle (1100-1500) */
    	ENM("English, Middle (1100-1500)"),
     
    	/** Esperanto */
    	EPO("Esperanto"),
     
    	/** Estonian */
    	EST("Estonian"),
     
    	/** Ewe */
    	EWE("Ewe"),
     
    	/** Ewondo */
    	EWO("Ewondo"),
     
    	/** Fang */
    	FAN("Fang"),
     
    	/** Faroese */
    	FAO("Faroese"),
     
    	/** Fanti */
    	FAT("Fanti"),
     
    	/** Fijian */
    	FIJ("Fijian"),
     
    	/** Filipino; Pilipino */
    	FIL("Filipino; Pilipino"),
     
    	/** Finnish */
    	FIN("Finnish"),
     
    	/** Finno-Ugrian (Other) */
    	FIU("Finno-Ugrian (Other)"),
     
    	/** Fon */
    	FON("Fon"),
     
    	/** French */
    	FRE("French"),
     
    	/** French, Middle (ca.1400-1600) */
    	FRM("French, Middle (ca.1400-1600)"),
     
    	/** French, Old (842-ca.1400) */
    	FRO("French, Old (842-ca.1400)"),
     
    	/** Northern Frisian */
    	FRR("Northern Frisian"),
     
    	/** Eastern Frisian */
    	FRS("Eastern Frisian"),
     
    	/** Western Frisian */
    	FRY("Western Frisian"),
     
    	/** Fulah */
    	FUL("Fulah"),
     
    	/** Friulian */
    	FUR("Friulian"),
     
    	/** Ga */
    	GAA("Ga"),
     
    	/** Gayo */
    	GAY("Gayo"),
     
    	/** Gbaya */
    	GBA("Gbaya"),
     
    	/** Germanic (Other) */
    	GEM("Germanic (Other)"),
     
    	/** Georgian */
    	GEO("Georgian"),
     
    	/** German */
    	GER("German"),
     
    	/** Geez */
    	GEZ("Geez"),
     
    	/** Gilbertese */
    	GIL("Gilbertese"),
     
    	/** Gaelic; Scottish Gaelic */
    	GLA("Gaelic; Scottish Gaelic"),
     
    	/** Irish */
    	GLE("Irish"),
     
    	/** Galician */
    	GLG("Galician"),
     
    	/** Manx */
    	GLV("Manx"),
     
    	/** German, Middle High (ca.1050-1500) */
    	GMH("German, Middle High (ca.1050-1500)"),
     
    	/** German, Old High (ca.750-1050) */
    	GOH("German, Old High (ca.750-1050)"),
     
    	/** Gondi */
    	GON("Gondi"),
     
    	/** Gorontalo */
    	GOR("Gorontalo"),
     
    	/** Gothic */
    	GOT("Gothic"),
     
    	/** Grebo */
    	GRB("Grebo"),
     
    	/** Greek, Ancient (to 1453) */
    	GRC("Greek, Ancient (to 1453)"),
     
    	/** Greek, Modern (1453-) */
    	GRE("Greek, Modern (1453-)"),
     
    	/** Guarani */
    	GRN("Guarani"),
     
    	/** Swiss German; Alemannic */
    	GSW("Swiss German; Alemannic"),
     
    	/** Gujarati */
    	GUJ("Gujarati"),
     
    	/** Gwich'in */
    	GWI("Gwich'in"),
     
    	/** Haida */
    	HAI("Haida"),
     
    	/** Haitian; Haitian Creole */
    	HAT("Haitian; Haitian Creole"),
     
    	/** Hausa */
    	HAU("Hausa"),
     
    	/** Hawaiian */
    	HAW("Hawaiian"),
     
    	/** Hebrew */
    	HEB("Hebrew"),
     
    	/** Herero */
    	HER("Herero"),
     
    	/** Hiligaynon */
    	HIL("Hiligaynon"),
     
    	/** Himachali */
    	HIM("Himachali"),
     
    	/** Hindi */
    	HIN("Hindi"),
     
    	/** Hittite */
    	HIT("Hittite"),
     
    	/** Hmong */
    	HMN("Hmong"),
     
    	/** Hiri Motu */
    	HMO("Hiri Motu"),
     
    	/** Upper Sorbian */
    	HSB("Upper Sorbian"),
     
    	/** Hungarian */
    	HUN("Hungarian"),
     
    	/** Hupa */
    	HUP("Hupa"),
     
    	/** Iban */
    	IBA("Iban"),
     
    	/** Igbo */
    	IBO("Igbo"),
     
    	/** Icelandic */
    	ICE("Icelandic"),
     
    	/** Ido */
    	IDO("Ido"),
     
    	/** Sichuan Yi */
    	III("Sichuan Yi"),
     
    	/** Ijo languages */
    	IJO("Ijo languages"),
     
    	/** Inuktitut */
    	IKU("Inuktitut"),
     
    	/** Interlingue */
    	ILE("Interlingue"),
     
    	/** Iloko */
    	ILO("Iloko"),
     
    	/** Interlingua (International Auxiliary Language Association) */
    	INA("Interlingua (International Auxiliary Language Association)"),
     
    	/** Indic (Other) */
    	INC("Indic (Other)"),
     
    	/** Indonesian */
    	IND("Indonesian"),
     
    	/** Indo-European (Other) */
    	INE("Indo-European (Other)"),
     
    	/** Ingush */
    	INH("Ingush"),
     
    	/** Inupiaq */
    	IPK("Inupiaq"),
     
    	/** Iranian (Other) */
    	IRA("Iranian (Other)"),
     
    	/** Iroquoian languages */
    	IRO("Iroquoian languages"),
     
    	/** Italian */
    	ITA("Italian"),
     
    	/** Javanese */
    	JAV("Javanese"),
     
    	/** Lojban */
    	JBO("Lojban"),
     
    	/** Japanese */
    	JPN("Japanese"),
     
    	/** Judeo-Persian */
    	JPR("Judeo-Persian"),
     
    	/** Judeo-Arabic */
    	JRB("Judeo-Arabic"),
     
    	/** Kara-Kalpak */
    	KAA("Kara-Kalpak"),
     
    	/** Kabyle */
    	KAB("Kabyle"),
     
    	/** Kachin; Jingpho */
    	KAC("Kachin; Jingpho"),
     
    	/** Kalaallisut; Greenlandic */
    	KAL("Kalaallisut; Greenlandic"),
     
    	/** Kamba */
    	KAM("Kamba"),
     
    	/** Kannada */
    	KAN("Kannada"),
     
    	/** Karen languages */
    	KAR("Karen languages"),
     
    	/** Kashmiri */
    	KAS("Kashmiri"),
     
    	/** Kanuri */
    	KAU("Kanuri"),
     
    	/** Kawi */
    	KAW("Kawi"),
     
    	/** Kazakh */
    	KAZ("Kazakh"),
     
    	/** Kabardian */
    	KBD("Kabardian"),
     
    	/** Khasi */
    	KHA("Khasi"),
     
    	/** Khoisan (Other) */
    	KHI("Khoisan (Other)"),
     
    	/** Central Khmer */
    	KHM("Central Khmer"),
     
    	/** Khotanese */
    	KHO("Khotanese"),
     
    	/** Kikuyu; Gikuyu */
    	KIK("Kikuyu; Gikuyu"),
     
    	/** Kinyarwanda */
    	KIN("Kinyarwanda"),
     
    	/** Kirghiz; Kyrgyz */
    	KIR("Kirghiz; Kyrgyz"),
     
    	/** Kimbundu */
    	KMB("Kimbundu"),
     
    	/** Konkani */
    	KOK("Konkani"),
     
    	/** Komi */
    	KOM("Komi"),
     
    	/** Kongo */
    	KON("Kongo"),
     
    	/** Korean */
    	KOR("Korean"),
     
    	/** Kosraean */
    	KOS("Kosraean"),
     
    	/** Kpelle */
    	KPE("Kpelle"),
     
    	/** Karachay-Balkar */
    	KRC("Karachay-Balkar"),
     
    	/** Karelian */
    	KRL("Karelian"),
     
    	/** Kru languages */
    	KRO("Kru languages"),
     
    	/** Kurukh */
    	KRU("Kurukh"),
     
    	/** Kuanyama; Kwanyama */
    	KUA("Kuanyama; Kwanyama"),
     
    	/** Kumyk */
    	KUM("Kumyk"),
     
    	/** Kurdish */
    	KUR("Kurdish"),
     
    	/** Kutenai */
    	KUT("Kutenai"),
     
    	/** Ladino */
    	LAD("Ladino"),
     
    	/** Lahnda */
    	LAH("Lahnda"),
     
    	/** Lamba */
    	LAM("Lamba"),
     
    	/** Lao */
    	LAO("Lao"),
     
    	/** Latin */
    	LAT("Latin"),
     
    	/** Latvian */
    	LAV("Latvian"),
     
    	/** Lezghian */
    	LEZ("Lezghian"),
     
    	/** Limburgan; Limburger; Limburgish */
    	LIM("Limburgan; Limburger; Limburgish"),
     
    	/** Lingala */
    	LIN("Lingala"),
     
    	/** Lithuanian */
    	LIT("Lithuanian"),
     
    	/** Mongo */
    	LOL("Mongo"),
     
    	/** Lozi */
    	LOZ("Lozi"),
     
    	/** Luxembourgish; Letzeburgesch */
    	LTZ("Luxembourgish; Letzeburgesch"),
     
    	/** Luba-Lulua */
    	LUA("Luba-Lulua"),
     
    	/** Luba-Katanga */
    	LUB("Luba-Katanga"),
     
    	/** Ganda */
    	LUG("Ganda"),
     
    	/** Luiseno */
    	LUI("Luiseno"),
     
    	/** Lunda */
    	LUN("Lunda"),
     
    	/** Luo (Kenya and Tanzania) */
    	LUO("Luo (Kenya and Tanzania)"),
     
    	/** Lushai */
    	LUS("Lushai"),
     
    	/** Macedonian */
    	MAC("Macedonian"),
     
    	/** Madurese */
    	MAD("Madurese"),
     
    	/** Magahi */
    	MAG("Magahi"),
     
    	/** Marshallese */
    	MAH("Marshallese"),
     
    	/** Maithili */
    	MAI("Maithili"),
     
    	/** Makasar */
    	MAK("Makasar"),
     
    	/** Malayalam */
    	MAL("Malayalam"),
     
    	/** Mandingo */
    	MAN("Mandingo"),
     
    	/** Maori */
    	MAO("Maori"),
     
    	/** Austronesian (Other) */
    	MAP("Austronesian (Other)"),
     
    	/** Marathi */
    	MAR("Marathi"),
     
    	/** Masai */
    	MAS("Masai"),
     
    	/** Malay */
    	MAY("Malay"),
     
    	/** Moksha */
    	MDF("Moksha"),
     
    	/** Mandar */
    	MDR("Mandar"),
     
    	/** Mende */
    	MEN("Mende"),
     
    	/** Irish, Middle (900-1200) */
    	MGA("Irish, Middle (900-1200)"),
     
    	/** Mi'kmaq; Micmac */
    	MIC("Mi'kmaq; Micmac"),
     
    	/** Minangkabau */
    	MIN("Minangkabau"),
     
    	/** Miscellaneous languages */
    	MIS("Miscellaneous languages"),
     
    	/** Mon-Khmer (Other) */
    	MKH("Mon-Khmer (Other)"),
     
    	/** Malagasy */
    	MLG("Malagasy"),
     
    	/** Maltese */
    	MLT("Maltese"),
     
    	/** Manchu */
    	MNC("Manchu"),
     
    	/** Manipuri */
    	MNI("Manipuri"),
     
    	/** Manobo languages */
    	MNO("Manobo languages"),
     
    	/** Mohawk */
    	MOH("Mohawk"),
     
    	/** Moldavian */
    	MOL("Moldavian"),
     
    	/** Mongolian */
    	MON("Mongolian"),
     
    	/** Mossi */
    	MOS("Mossi"),
     
    	/** Multiple languages */
    	MUL("Multiple languages"),
     
    	/** Munda languages */
    	MUN("Munda languages"),
     
    	/** Creek */
    	MUS("Creek"),
     
    	/** Mirandese */
    	MWL("Mirandese"),
     
    	/** Marwari */
    	MWR("Marwari"),
     
    	/** Mayan languages */
    	MYN("Mayan languages"),
     
    	/** Erzya */
    	MYV("Erzya"),
     
    	/** Nahuatl languages */
    	NAH("Nahuatl languages"),
     
    	/** North American Indian */
    	NAI("North American Indian"),
     
    	/** Neapolitan */
    	NAP("Neapolitan"),
     
    	/** Nauru */
    	NAU("Nauru"),
     
    	/** Navajo; Navaho */
    	NAV("Navajo; Navaho"),
     
    	/** Ndebele, South; South Ndebele */
    	NBL("Ndebele, South; South Ndebele"),
     
    	/** Ndebele, North; North Ndebele */
    	NDE("Ndebele, North; North Ndebele"),
     
    	/** Ndonga */
    	NDO("Ndonga"),
     
    	/** Low German; Low Saxon; German, Low; Saxon, Low */
    	NDS("Low German; Low Saxon; German, Low; Saxon, Low"),
     
    	/** Nepali */
    	NEP("Nepali"),
     
    	/** Nepal Bhasa; Newari */
    	NEW("Nepal Bhasa; Newari"),
     
    	/** Nias */
    	NIA("Nias"),
     
    	/** Niger-Kordofanian (Other) */
    	NIC("Niger-Kordofanian (Other)"),
     
    	/** Niuean */
    	NIU("Niuean"),
     
    	/** Norwegian Nynorsk; Nynorsk, Norwegian */
    	NNO("Norwegian Nynorsk; Nynorsk, Norwegian"),
     
    	/** Bokmål, Norwegian; Norwegian Bokmål */
    	NOB("Bokmål, Norwegian; Norwegian Bokmål"),
     
    	/** Nogai */
    	NOG("Nogai"),
     
    	/** Norse, Old */
    	NON("Norse, Old"),
     
    	/** Norwegian */
    	NOR("Norwegian"),
     
    	/** N'Ko */
    	NQO("N'Ko"),
     
    	/** Pedi; Sepedi; Northern Sotho */
    	NSO("Pedi; Sepedi; Northern Sotho"),
     
    	/** Nubian languages */
    	NUB("Nubian languages"),
     
    	/** Classical Newari; Old Newari; Classical Nepal Bhasa */
    	NWC("Classical Newari; Old Newari; Classical Nepal Bhasa"),
     
    	/** Chichewa; Chewa; Nyanja */
    	NYA("Chichewa; Chewa; Nyanja"),
     
    	/** Nyamwezi */
    	NYM("Nyamwezi"),
     
    	/** Nyankole */
    	NYN("Nyankole"),
     
    	/** Nyoro */
    	NYO("Nyoro"),
     
    	/** Nzima */
    	NZI("Nzima"),
     
    	/** Occitan (post 1500); Provençal */
    	OCI("Occitan (post 1500); Provençal"),
     
    	/** Ojibwa */
    	OJI("Ojibwa"),
     
    	/** Oriya */
    	ORI("Oriya"),
     
    	/** Oromo */
    	ORM("Oromo"),
     
    	/** Osage */
    	OSA("Osage"),
     
    	/** Ossetian; Ossetic */
    	OSS("Ossetian; Ossetic"),
     
    	/** Turkish, Ottoman (1500-1928) */
    	OTA("Turkish, Ottoman (1500-1928)"),
     
    	/** Otomian languages */
    	OTO("Otomian languages"),
     
    	/** Papuan (Other) */
    	PAA("Papuan (Other)"),
     
    	/** Pangasinan */
    	PAG("Pangasinan"),
     
    	/** Pahlavi */
    	PAL("Pahlavi"),
     
    	/** Pampanga */
    	PAM("Pampanga"),
     
    	/** Panjabi; Punjabi */
    	PAN("Panjabi; Punjabi"),
     
    	/** Papiamento */
    	PAP("Papiamento"),
     
    	/** Palauan */
    	PAU("Palauan"),
     
    	/** Persian, Old (ca.600-400 B.C.) */
    	PEO("Persian, Old (ca.600-400 B.C.)"),
     
    	/** Persian */
    	PER("Persian"),
     
    	/** Philippine (Other) */
    	PHI("Philippine (Other)"),
     
    	/** Phoenician */
    	PHN("Phoenician"),
     
    	/** Pali */
    	PLI("Pali"),
     
    	/** Polish */
    	POL("Polish"),
     
    	/** Pohnpeian */
    	PON("Pohnpeian"),
     
    	/** Portuguese */
    	POR("Portuguese"),
     
    	/** Prakrit languages */
    	PRA("Prakrit languages"),
     
    	/** Provençal, Old (to 1500) */
    	PRO("Provençal, Old (to 1500)"),
     
    	/** Pushto */
    	PUS("Pushto"),
     
    	/** Reserved for local use */
    	QAA_QTZ("Reserved for local use"),
     
    	/** Quechua */
    	QUE("Quechua"),
     
    	/** Rajasthani */
    	RAJ("Rajasthani"),
     
    	/** Rapanui */
    	RAP("Rapanui"),
     
    	/** Rarotongan; Cook Islands Maori */
    	RAR("Rarotongan; Cook Islands Maori"),
     
    	/** Romance (Other) */
    	ROA("Romance (Other)"),
     
    	/** Romansh */
    	ROH("Romansh"),
     
    	/** Romany */
    	ROM("Romany"),
     
    	/** Romanian */
    	RUM("Romanian"),
     
    	/** Rundi */
    	RUN("Rundi"),
     
    	/** Aromanian; Arumanian; Macedo-Romanian */
    	RUP("Aromanian; Arumanian; Macedo-Romanian"),
     
    	/** Russian */
    	RUS("Russian"),
     
    	/** Sandawe */
    	SAD("Sandawe"),
     
    	/** Sango */
    	SAG("Sango"),
     
    	/** Yakut */
    	SAH("Yakut"),
     
    	/** South American Indian (Other) */
    	SAI("South American Indian (Other)"),
     
    	/** Salishan languages */
    	SAL("Salishan languages"),
     
    	/** Samaritan Aramaic */
    	SAM("Samaritan Aramaic"),
     
    	/** Sanskrit */
    	SAN("Sanskrit"),
     
    	/** Sasak */
    	SAS("Sasak"),
     
    	/** Santali */
    	SAT("Santali"),
     
    	/** Serbian */
    	SCC("Serbian"),
     
    	/** Sicilian */
    	SCN("Sicilian"),
     
    	/** Scots */
    	SCO("Scots"),
     
    	/** Croatian */
    	SCR("Croatian"),
     
    	/** Selkup */
    	SEL("Selkup"),
     
    	/** Semitic (Other) */
    	SEM("Semitic (Other)"),
     
    	/** Irish, Old (to 900) */
    	SGA("Irish, Old (to 900)"),
     
    	/** Sign Languages */
    	SGN("Sign Languages"),
     
    	/** Shan */
    	SHN("Shan"),
     
    	/** Sidamo */
    	SID("Sidamo"),
     
    	/** Sinhala; Sinhalese */
    	SIN("Sinhala; Sinhalese"),
     
    	/** Siouan languages */
    	SIO("Siouan languages"),
     
    	/** Sino-Tibetan (Other) */
    	SIT("Sino-Tibetan (Other)"),
     
    	/** Slavic (Other) */
    	SLA("Slavic (Other)"),
     
    	/** Slovak */
    	SLO("Slovak"),
     
    	/** Slovenian */
    	SLV("Slovenian"),
     
    	/** Southern Sami */
    	SMA("Southern Sami"),
     
    	/** Northern Sami */
    	SME("Northern Sami"),
     
    	/** Sami languages (Other) */
    	SMI("Sami languages (Other)"),
     
    	/** Lule Sami */
    	SMJ("Lule Sami"),
     
    	/** Inari Sami */
    	SMN("Inari Sami"),
     
    	/** Samoan */
    	SMO("Samoan"),
     
    	/** Skolt Sami */
    	SMS("Skolt Sami"),
     
    	/** Shona */
    	SNA("Shona"),
     
    	/** Sindhi */
    	SND("Sindhi"),
     
    	/** Soninke */
    	SNK("Soninke"),
     
    	/** Sogdian */
    	SOG("Sogdian"),
     
    	/** Somali */
    	SOM("Somali"),
     
    	/** Songhai languages */
    	SON("Songhai languages"),
     
    	/** Sotho, Southern */
    	SOT("Sotho, Southern"),
     
    	/** Spanish; Castilian */
    	SPA("Spanish; Castilian"),
     
    	/** Sardinian */
    	SRD("Sardinian"),
     
    	/** Sranan Tongo */
    	SRN("Sranan Tongo"),
     
    	/** Serer */
    	SRR("Serer"),
     
    	/** Nilo-Saharan (Other) */
    	SSA("Nilo-Saharan (Other)"),
     
    	/** Swati */
    	SSW("Swati"),
     
    	/** Sukuma */
    	SUK("Sukuma"),
     
    	/** Sundanese */
    	SUN("Sundanese"),
     
    	/** Susu */
    	SUS("Susu"),
     
    	/** Sumerian */
    	SUX("Sumerian"),
     
    	/** Swahili */
    	SWA("Swahili"),
     
    	/** Swedish */
    	SWE("Swedish"),
     
    	/** Syriac */
    	SYR("Syriac"),
     
    	/** Tahitian */
    	TAH("Tahitian"),
     
    	/** Tai (Other) */
    	TAI("Tai (Other)"),
     
    	/** Tamil */
    	TAM("Tamil"),
     
    	/** Tatar */
    	TAT("Tatar"),
     
    	/** Telugu */
    	TEL("Telugu"),
     
    	/** Timne */
    	TEM("Timne"),
     
    	/** Tereno */
    	TER("Tereno"),
     
    	/** Tetum */
    	TET("Tetum"),
     
    	/** Tajik */
    	TGK("Tajik"),
     
    	/** Tagalog */
    	TGL("Tagalog"),
     
    	/** Thai */
    	THA("Thai"),
     
    	/** Tibetan */
    	TIB("Tibetan"),
     
    	/** Tigre */
    	TIG("Tigre"),
     
    	/** Tigrinya */
    	TIR("Tigrinya"),
     
    	/** Tiv */
    	TIV("Tiv"),
     
    	/** Tokelau */
    	TKL("Tokelau"),
     
    	/** Klingon; tlhIngan-Hol */
    	TLH("Klingon; tlhIngan-Hol"),
     
    	/** Tlingit */
    	TLI("Tlingit"),
     
    	/** Tamashek */
    	TMH("Tamashek"),
     
    	/** Tonga (Nyasa) */
    	TOG("Tonga (Nyasa)"),
     
    	/** Tonga (Tonga Islands) */
    	TON("Tonga (Tonga Islands)"),
     
    	/** Tok Pisin */
    	TPI("Tok Pisin"),
     
    	/** Tsimshian */
    	TSI("Tsimshian"),
     
    	/** Tswana */
    	TSN("Tswana"),
     
    	/** Tsonga */
    	TSO("Tsonga"),
     
    	/** Turkmen */
    	TUK("Turkmen"),
     
    	/** Tumbuka */
    	TUM("Tumbuka"),
     
    	/** Tupi languages */
    	TUP("Tupi languages"),
     
    	/** Turkish */
    	TUR("Turkish"),
     
    	/** Altaic (Other) */
    	TUT("Altaic (Other)"),
     
    	/** Tuvalu */
    	TVL("Tuvalu"),
     
    	/** Twi */
    	TWI("Twi"),
     
    	/** Tuvinian */
    	TYV("Tuvinian"),
     
    	/** Udmurt */
    	UDM("Udmurt"),
     
    	/** Ugaritic */
    	UGA("Ugaritic"),
     
    	/** Uighur; Uyghur */
    	UIG("Uighur; Uyghur"),
     
    	/** Ukrainian */
    	UKR("Ukrainian"),
     
    	/** Umbundu */
    	UMB("Umbundu"),
     
    	/** Undetermined */
    	UND("Undetermined"),
     
    	/** Urdu */
    	URD("Urdu"),
     
    	/** Uzbek */
    	UZB("Uzbek"),
     
    	/** Vai */
    	VAI("Vai"),
     
    	/** Venda */
    	VEN("Venda"),
     
    	/** Vietnamese */
    	VIE("Vietnamese"),
     
    	/** Volapük */
    	VOL("Volapük"),
     
    	/** Votic */
    	VOT("Votic"),
     
    	/** Wakashan languages */
    	WAK("Wakashan languages"),
     
    	/** Walamo */
    	WAL("Walamo"),
     
    	/** Waray */
    	WAR("Waray"),
     
    	/** Washo */
    	WAS("Washo"),
     
    	/** Welsh */
    	WEL("Welsh"),
     
    	/** Sorbian languages */
    	WEN("Sorbian languages"),
     
    	/** Walloon */
    	WLN("Walloon"),
     
    	/** Wolof */
    	WOL("Wolof"),
     
    	/** Kalmyk; Oirat */
    	XAL("Kalmyk; Oirat"),
     
    	/** Xhosa */
    	XHO("Xhosa"),
     
    	/** Yao */
    	YAO("Yao"),
     
    	/** Yapese */
    	YAP("Yapese"),
     
    	/** Yiddish */
    	YID("Yiddish"),
     
    	/** Yoruba */
    	YOR("Yoruba"),
     
    	/** Yupik languages */
    	YPK("Yupik languages"),
     
    	/** Zapotec */
    	ZAP("Zapotec"),
     
    	/** Zenaga */
    	ZEN("Zenaga"),
     
    	/** Zhuang; Chuang */
    	ZHA("Zhuang; Chuang"),
     
    	/** Zande languages */
    	ZND("Zande languages"),
     
    	/** Zulu */
    	ZUL("Zulu"),
     
    	/** Zuni */
    	ZUN("Zuni"),
     
    	/** No linguistic content */
    	ZXX("No linguistic content"),
     
    	/** Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki */
    	ZZA("Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki");
     
    	/** Language description. */
    	private String desc;
     
    	/**
             * Creates a language.
             * 
             * @param desc
             *            Language description.
             */
    	Language(String desc) {
    		this.desc = desc;
    	}
     
    	/**
             * Returns the description of the language.
             * 
             * @return Language description.
             */
    	public String getDescription() {
    		return desc;
    	}
     
    	/**
             * Returns the 3-letters code, lower-cased.
             * 
             * @return 3-letters code.
             */
    	public String getCode() {
    		return name().toLowerCase();
    	}
     
    }
      0  0

  14. #54
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut Message de progression dans la console
    Voici une classe qui permet d'afficher la progression d'un travail à priori non graphique dans la console texte.

    L'avantage est la lisibilité du message, il tient et se rafraîchit sur une seule ligne, ça n'inonde pas la console et ça permet par exemple de trouver à quel pas un processus plante ou ralentit, ou de visualiser la progression d'un algorithme de compression ou de cryptage.

    Auteur : anadoncamille
    Merci à ®om

    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
     
    import java.util.Date;
    import java.text.SimpleDateFormat;
    /*
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
     
    public class ProgressMessage {
     
      /* Une fonction qui affiche sur une ligne de console la progression d'une tâche.
       *
       * Elle s'utilise par exemple dans une boucle for ou dans tout processus qui 
       * contient un nombre d'étapes bien défini.
       *
       * Les messages sont en anglais, libre à vous de les modifier
       */
      public static void printPercent(float step, float stepsCount) {
        // Calcul du pourcentage de progression
        float step_1 = step + 1;
        int percent = Math.round(step_1 * 100 / stepsCount);
        // Si la tâche n'est pas encore finie, ne pas afficher 100%, mais s'arrêter à 99%
        if (percent >= 100)
          percent = 99;
        // Stockge du pourcentage
        String message = "" + percent + "%";
        // Si le pourcentage est inférieur à 10, ajouter un esapce devant
        if (percent < 10)
          message = " " + message; 
        if (step_1 >= stepsCount)
          // Si le boulot est fini, changer de message, afficher lengthfait que c'est fini
          message = "job done, " + (int)stepsCount + " steps.                                                     \n";
        else
          // Sinon, ajouter l'heure au message, puis le pas en cours et le nombre de pas
          message = message + " - " + getHour() + " - step " + (int)(step_1) + "/" + (int)stepsCount;
        // Ramener le curseur en début de ligne
        System.out.print("\r");
        // Si c'est le premier pas, afficher le message de début et retourner à la ligne
        if (step == 0)
          System.out.println("  " + getHour() + "  Starting job.");
        // Si c'est le dernier pas, afficher l'heure
        if (step_1 >= stepsCount)
          System.out.print("  " + getHour());
        // Afficher lengthmessage créé
        System.out.print("  Working : " + message);
      }
     
      // Une fonction très simple pour obtenir l'heure formattée sous forme de chaîne de caractères
      public static String getHour() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
      }
     
      // Exemple d'utilisation, une boucle infinie permet d'apprécier l'affichage de fin :)
      public static void main(String[] args) {
        int count = 9999;
        for (int i = 0 ; i < count ; i++) {
          /* Votre code ici, 
           * évitez les messages dans System.out
           */
          printPercent(i, count);
        }
        System.out.println("\n2007 Sylvain Tournois - http://sylv.tournois.free.fr/");
        System.out.println("\nPressez Ctrl-C pour terminer le programme.");
        while (true);
      }
     
    }
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

  15. #55
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut ZIP / UNZIP simple, efficace
    Bonjour,

    Voici le code d'un zipper/dézippeur simple à utiliser, rapide et efficace.

    Auteur : anadoncamille

    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
     
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.RandomAccessFile;
     
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Vector;
     
    import java.util.zip.ZipOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
     
    /* Un (dé)compresseur simple d'utilisation, rapide et efficace.
     *
     * Deux méthodes principales :
     *
     * Deux méthodes principales : 
     *   - zip(String directory) // compresse un dossier dans un fichier de même nom
     *   - unzip(String file) // décompresse un fichier dans un dossier de même nom
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class Ziper {
     
      // Compresse le répertoire "monDossier" dans le fichier "monDossier.zip"
      public static void zip(String directory) {
        System.out.println("Archiving directory " + directory + " in file " + directory + ".zip :");
        try {
          FileOutputStream fos = new FileOutputStream(directory + ".zip");
          ZipOutputStream zos = new ZipOutputStream(fos);
          Vector entries = getFileList(directory, "*");
          int n = entries.size();
          String s;
          String s2;
          ZipEntry ze;
          RandomAccessFile raf = null;
          byte[] bb;
          int l = directory.length() + 1;
          for (int i = 0 ; i < n ; i++) {
            s = (String)entries.get(i);
            s2 = s.substring(l);
            raf = new RandomAccessFile(s, "r");
            bb = new byte[(int)raf.length()];
            raf.read(bb);
            ze = new ZipEntry(s2);
            zos.putNextEntry(ze);
            zos.write(bb);
            raf.close();
            printPercent(i, n);
          }
          zos.finish();
          System.out.println("\nArchiving done. Thank you for using me!");
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Décompresse le fichier "monFichier.zip" dan le répertoire "monFichier"
      public static void unzip(String file) {
        try {
          String directory = file.substring(0, file.lastIndexOf(".")) + "/";
          System.out.println("Extracting file " + file + " in directory " + directory + " :");
          ZipFile zf = new ZipFile(file);
          ZipEntry ze;
          Hashtable ht = new Hashtable();
          int nf = 0;
          Enumeration e = zf.entries();
          for ( ; e.hasMoreElements() ; ) {
            ze = (ZipEntry)e.nextElement();
            ht.put(ze.getName(), ze);
            nf++;
          }
          RandomAccessFile raf = new RandomAccessFile(file, "r");
          byte[] bb = new byte[(int)raf.length()];
          raf.read(bb);
          raf.close();
          ByteArrayInputStream bais = new ByteArrayInputStream(bb);
          ZipInputStream zis = new ZipInputStream(bais);
          ze = zis.getNextEntry();
          String s;
          int i;
          int n;
          int l;
          int n2 = 0;
          while (ze != null) {
            ze = (ZipEntry)ht.get(ze.getName());
            s = directory + ze.getName();
            bb = new byte[(int)ze.getSize()];
            i = 0;
            l = bb.length;
            while (l > 0) {
              n = zis.read(bb, i, l);
              i += n;
              l -= n;
            }
            createFile(s);
            raf = new RandomAccessFile(s, "rw");
            raf.write(bb);
            raf.close();
            ze = zis.getNextEntry();
            printPercent(n2, nf);
            n2++;
          }
        }
        catch (Exception e) {
          e.printStackTrace();
        }
        System.out.println("\nExtracting done. Thank you for using me!");
      }
     
      // Crée un fichier vide de nom "monDossier/mesRubriques/monFichier.machin" et le chemin qui y mène
      public static void createFile(String fileName) {
        if (fileName.indexOf('/') > 0) {
          File f = new File(fileName.substring(0, fileName.lastIndexOf('/')));
          f.mkdirs();
        }
        File f = new File(fileName);
        try {
          FileWriter fw = new FileWriter(fileName, false);
          fw.close();
        }
        catch (Exception e) {
        }
      }
     
      // Transforme un nom de fichier "a\b\..\c\d.txt" en "a/c/d.txt"
      public static String reduceFileName(String s) {
        String s2 = s.replace('\\', '/');
        String[] words = s2.split("/");
        boolean[] ok = new boolean[words.length];
        for (int i = 0 ; i < words.length ; i++) 
          ok[i] = true;
        for (int i = words.length - 1 ; i >= 0 ; i--) {
          if (words[i].equals("..")) {
            int j = i - 1;
            while ((j >= 0) && ((words[j].equals("..")) || (!ok[j])))
              j--;
            if (j >= 0) {
              ok[i] = false;
              ok[j] = false;
            }
          }
        }
        s2 = "";
        for (int i = 0 ; i < words.length - 1 ; i++)
          if (ok[i])
            s2 += words[i] + "/";
        return s2 + words[words.length - 1];
      }
     
      // Affiche la progression de la (dé)compression
      public static void printPercent(float step, float stepsCount) {
        float step_1 = step + 1;
        int percent = Math.round(step_1 * 100 / stepsCount);
        if (percent >= 100)
          percent = 99;
        String message = "" + percent + "%";
        if (percent < 10)
          message = " " + message; 
        if (step_1 >= stepsCount)
          message = "job done, " + (int)stepsCount + " steps.                                                     \n";
        else
          message = message + " - " + getHour() + " - step " + (int)(step_1) + "/" + (int)stepsCount;
        System.out.print("\r");
        if (step == 0)
          System.out.println("  " + getHour() + "  Starting job.");
        if (step_1 >= stepsCount)
          System.out.print("  " + getHour());
        System.out.print("  Working : " + message);
      }
     
      // Renvoie l'heure dans une chaîne de caractères
      public static String getHour() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
      }
     
      // Renvoie la liste des fihiers "*.monExtension" contenus contenue dans l'arborescence "monDossier"
      public static Vector getFileList(String directory, String extension) {
        return getFileList(directory, "", extension);
      }
     
      // Renvoie la liste des fichiers "monDebut*.monExtension" contenus contenue dans l'arborescence "monDossier"
      public static Vector getFileList(String directory, String start, String extension) {
        Vector result = new Vector();
        File f = new File(directory);
        File[] list = f.listFiles(new DirFileFilter());
        if ((list != null) && (list.length != 0))
          for (int i = 0 ; i < list.length ; i++)
            result.addAll(getFileList(f.getPath() + "\\" + list[i].getName(), extension));
        list = f.listFiles(new GenFileFilter(start, extension));
        String n;
        if ((list != null) && (list.length != 0))
          for (int i = 0 ; i < list.length ; i++) {
            n = reduceFileName(f.getPath() + "\\" + list[i].getName());
            result.add(n);
          }
        return result;
      }
     
      // Cette classe sert à filtrer les répertoires dans les fichiers
      private static class DirFileFilter implements FileFilter {
     
        public DirFileFilter() {
        }
     
        public boolean accept(File f) {
          return f.isDirectory();
        }
     
      }
     
      // Une classe filtre générique, sélectionne les fichiers "monDebut*.monExtension"
      private static class GenFileFilter implements FileFilter {
     
        private String start;
        private String extension;
        private boolean allFiles;
        private boolean allExts;
     
        public GenFileFilter(String ext) {
          start = "";
          extension = new String(ext);
          extension = extension.toLowerCase();
          allExts = extension.equals("*");
          allFiles = allExts;
        }
     
        public GenFileFilter(String s, String ext) {
          start = new String(s);
          start = start.toLowerCase();
          extension = new String(ext);
          extension = extension.toLowerCase();
          allExts = extension.equals("*");
          allFiles = allExts && start.equals("*");
        }
     
        public boolean accept(File f) {
          if (!f.isFile())
            return false;
          if (allFiles)
            return true;
          String n = f.getName();
          if (n.length() < start.length())
            return false;
          n = n.toLowerCase();
          String tst = n.substring(0, start.length());
          if (!tst.equals(start))
            return false;
          if (allExts)
            return true;
          if (n.lastIndexOf(".") < 0)
            return false;
          tst = n.substring(n.lastIndexOf(".") + 1, n.length());
          return tst.equals(extension);
        }
     
      }
     
    }
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

  16. #56
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut Ajouter du mystère dans mon programme, Java
    Bonjour,

    Suite au post suivant http://www.developpez.net/forums/sho...36#post2361336 sur une façon d'ajouter du mystère dans un programme, voici un code qui montre différentes façon d'utiliser la classe Random du langage Java.

    L'application est une JFrame très simple qui affiche des codes et les résultats associés, 4 exemples de programmation autour de la classe Random.

    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
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
     
    /* Voici un code peu commenté mais fait pour montrer les potentiels et limites de 
     * la classe Random, fournisseuse de nombres pour Java.
     *
     * En faisant fonctionner ce programme, vous verrez les résultats produits par 
     * différentes utilisation de la classe Random.
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class RandomDemo extends JFrame implements MouseMotionListener {
     
      // Affichage des résultats
      private void boucle() {
        long refreshDate = System.currentTimeMillis();
        Random cyclic = new Random(refreshDate);
        long x = new Random().nextLong();
        userData = refreshDate;
        while (true) {
          Random rand = new Random();
          Random dead = new Random(x);
          Random alive = new Random(userData);
          labels[NUMBER0].setText("r0 == " + cyclic.nextLong() + "\nr1 == " + cyclic.nextLong() + "\nr2 == " + cyclic.nextLong());
          labels[NUMBER1].setText("r0 == " + rand.nextLong() + "\nr1 == " + rand.nextLong() + "\nr2 == " + rand.nextLong());
          labels[NUMBER2].setText("x == " + x + "\nr0 == " + dead.nextLong() + "\nr1 == " + dead.nextLong() + "\nr2 == " + dead.nextLong());
          labels[NUMBER3].setText("y == " + userData + "\nr0 == " + alive.nextLong() + "\nr1 == " + alive.nextLong() + "\nr2 == " + alive.nextLong());
          if (System.currentTimeMillis() > refreshDate) {
            x++;
            refreshDate += 1111;
          }
        }
      }
     
      // Modification de la variable userData
      public void mouseMoved(MouseEvent mouseEvent) {
        userData += mouseEvent.getX() + mouseEvent.getY();
        System.out.println("Mouse moved");
      }
     
      // Modification de la variable userData
      public void mouseDragged(MouseEvent mouseEvent) {
        userData += mouseEvent.getX() * mouseEvent.getY();
        System.out.println("Mouse dragged");
      }
     
      // Point d'entrée Java
      public static void main(String[] args) {
        new RandomDemo();
      }
     
      private static final int NAME0 = 0;
      private static final int NAME1 = 2;
      private static final int NAME2 = 4;
      private static final int NAME3 = 6;
      private static final int NUMBER0 = 1;
      private static final int NUMBER1 = 3;
      private static final int NUMBER2 = 5;
      private static final int NUMBER3 = 7;
      private static final int LABELS_COUNT = 8;
      private static final String[] TEXTS = {
        "Random rand = new Random();\nwhile(true) {\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
        "while(true) {\n  Random rand = new Random();\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
        "while(true){\n  Random rand = new Random(x);\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
        "while(true){\n  y += userActions()\n  Random rand = new Random(y);\n  long r0 = rand.nextLong();\n  long r1 = rand.nextLong();\n  long r2 = rand.nextLong();\n}",
        "",
      };
     
      private JTextArea[] labels;
      private long userData;
     
      public RandomDemo() {
        super("Potentiel du Random et Random potentiel - 2007 Sylvain Tournois - http://sylv.tournois.free.fr/");
        System.out.println("Potentiel du Random et Random potentiel");
        System.out.println("\n Copyright 2007   Sylvain Tournois\n\n http://sylv.tournois.free.fr/\n");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            exit();
          }
        });
        setBounds(0, 0, 640, 480);
        setLayout(new GridLayout(LABELS_COUNT / 2, 4));
        labels = new JTextArea[LABELS_COUNT];
        for (int i = 0 ; i < LABELS_COUNT ; i++) {
          labels[i] = new JTextArea(TEXTS[i]);
          labels[i].addMouseMotionListener(this);
          add(labels[i]);
        }
        addMouseMotionListener(this);
        setVisible(true);
        requestFocus();
        boucle();
      }
     
      private void exit() {
        System.exit(0);
      }
     
    }
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

  17. #57
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut Sauver des images opaques JPG, PNG, GIF
    Pour faire des screen shots ou enregistrer des images rendues, voici un enregistreur d'images simple, bien commenté :

    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
     
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.File;
     
    /* Un simple  enregistreur d'images.
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class ImageSaver {
     
      // Enregistre une image et indique si l'opération s'est bien déroulée
      public static boolean save(BufferedImage img, String s) {
        // si l'image n'a pas de contenu ou si le nom est vide, sortir en indiquant l'échec
        if ((img == null) || (s == null))
          return false;
        // récupère le format dans le nom : "png", "jpg" ou "gif"
        String format = s.substring(s.lastIndexOf(".") + 1).toUpperCase();
        // affiche un message dans la console
        System.out.print("Saving image " + s + " (" + format + ") : ");
        // Crée un objet fichier
        File file = new File(s);
        // Complète l'arborescence qui mène au fichier
        file.mkdirs();
        // Récupération d'exceptions
        try {
          // Ecriture du fichier, enregistrement de l'image
          ImageIO.write(img, format, file);
        }
        // En cas d'erreur
        catch (Exception e) {
          System.out.println("ERROR!");
          // Afficher le message de l'exception
          e.printStackTrace();
          // Sortir de la fonction en indiquant l'échec
          return false;
        }
        // On n'est pas sorti => pas d'erreur
        // Afficher le message de bon déroulement
        System.out.println("OK.");
        // Sortir de la fonction en indiquant la réussite
        return true;
      }
     
    }
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

  18. #58
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut Une JFrame qui enregistre son affichage
    Bonjour,

    voici une JFrame qui peut faire des impressions d'écran.

    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
     
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.imageio.*;
    import java.io.*;
     
    /* Une JFrame pour faire des screen shots
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class JFrameScreenShot extends JFrame implements KeyListener {
     
      // Configuration graphique de l'environnement de travail
      public static final GraphicsConfiguration DGC = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
     
      // Notre buffer de capture, de même taille que notre Frame
      private BufferedImage buffer;
      // Le fournisseur de services graphiques associé au buffer
      private Graphics2D graphics;
     
      public JFrameScreenShot(int width, int height) {
        // Crée la Frame
        super("test");
     
        // crée le buffer de la même taille que la fenêtre
        buffer = DGC.createCompatibleImage(width, height);
        // crée le fournisseur de services associé au buffer
        graphics = buffer.createGraphics();
     
        // Par défaut : on quitte l'application en fermant la fenêtre
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            exit();
          }
        });
     
        // Paramètres de position et taille de la fenêtre : 
        // position = 0, 0
        // taille = width X height
        setBounds(0, 0, width, height);
     
        // Afficher la fenêtre
        setVisible(true);
     
        // L'application est sensible au clavier
        addKeyListener(this);
     
        // Demande de focus (pour connecter au clavier)
        requestFocus();
      }
     
      private void exit() {
        System.exit(0);
      }
     
      // Point d'entrée Java
      public static void main(String[] args) {
        new JFrameScreenShot(640, 480);
      }
     
      // Cas de touche enfoncée
      public void keyPressed(KeyEvent keyEvent) {
      }
     
      // Cas de touche relâchée
      public void keyReleased(KeyEvent keyEvent) {
        // Capture de JFrame
        screenShot();
      }
     
      // Cas de caractère écrit
      public void keyTyped(KeyEvent keyEvent) {
      }
     
      // Capture de JFrame
      public void screenShot() {
        // Peint les composants de la JFrame dans le buffer
        paintAll(graphics);
        // Enregistre le buffer 
        save(buffer, "test.png");
      }
     
      // Enregistre une image
      public static boolean save(BufferedImage img, String s) {
        if ((img == null) || (s == null))
          return false;
        String format = s.substring(s.lastIndexOf(".") + 1).toUpperCase();
        System.out.print("Saving image " + s + " (" + format + ") : ");
        File file = new File(s);
        file.mkdirs();
        try {
          ImageIO.write(img, format, file);
        }
        catch (Exception e) {
          System.out.println("ERROR!");
          e.printStackTrace();
          return false;
        }
        System.out.println("OK.");
        return true;
      }
     
    }
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

  19. #59
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut Enregistrer des fichiers textes
    Voici une classe simple pour enregistrer des fichiers texte :

    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
     
    import java.io.File;
    import java.io.FileWriter;
    import java.io.BufferedWriter;
    import java.util.Vector;
     
    /* Une classe pour écrire simplement des fichiers textes.
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class TextFileWriter {
     
      private String fileName;
     
      // Crée un fichier en mode création
      public TextFileWriter(String fileName) {
        this(fileName, false);
      }
     
      // Crée un fichier en mode ajout o/n (si n, mode création)
      public TextFileWriter(String fileName, boolean append) {
        if (fileName.indexOf('/') > 0) {
          File f = new File(fileName.substring(0, fileName.lastIndexOf('/')));
          f.mkdirs();
        }
        this.fileName = new String(fileName);
        File f = new File(fileName);
        try {
          FileWriter fw = new FileWriter(fileName, append);
          fw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Ajoute une ligne
      public void addLine(String line) {
        try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
          bw.write(line);
          bw.newLine();
          bw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Ajoute plusieurs lignes
      public void addLines(Vector lines) {
        try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
          int n = lines.size();
          String s;
          for (int i = 0 ; i < n ; i++) {
            s = (String)lines.get(i);
            if (s != null) {
              bw.write(s);
              bw.newLine();
            }
          }
          bw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Ajoute plusieurs lignes
      public void addLines(String[] lines) {
        try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
          for (int i = 0 ; i < lines.length ; i++) {
            if (lines[i] != null) {
              bw.write(lines[i]);
              bw.newLine();
            }
          }
          bw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
     
      // Exemples d'utilisation
      public static void main(String[] args) {
        TextFileWriter tfw = new TextFileWriter("test.txt");
        tfw.addLine("Coucou");
        tfw.addLine("\n Copyright 2007   Sylvain Tournois\n\n www.anadoncamille.com\n");
        Vector v = new Vector();
        v.add("Ceci est un test");
        v.add("pour la classe");
        v.add("TextFileWriter");
        tfw.addLines(v);
      }
     
    }
    Dans le projet commons-io de Jakarta, vous retrouvez la même fonctionnalité avec la méthode writeLines(File, List). (merci Napalm51)
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

  20. #60
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut Oracle
    Bonjour,

    Voici un exemple simple d'oracle, basé sur un Random généré selon la philosophie décrite dans le post "Ajouter du mystère dans mon programme"

    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
     
    import java.util.Random;
    import java.util.Vector;
     
    /* Un oracle simple et souple, pour étudier le principe de Random.
     * L'algorithme est volontairement décomposé en étapes simples, il peut être 
     * codé de façon plus courte, tout en produisant le même résultat.
     *
     * 2007 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
    public class MiniOracle {
     
      // Choisit aléatoirement un message parmi ceux proposés
      public static String say(Vector messages) {
        // Equivalent à l'appel suivant : Random random = new Random(System.currentTimeMillis());
        // Crée un générateur de nombres basé sur la date d'appel de la méthode
        Random random = new Random();
        // Nombre de messages, nombre de faces du dé
        long n = messages.size();
        // Tirage du dé à n faces
        long d = random.nextLong() % n;
        // Envoi du message correspondant
        return (String)messages.get((int)d);
      }
     
      // Choisit aléatoirement un message parmi ceux proposés
      public static String say(String[] messages) {
        // Equivalent à l'appel suivant : Random random = new Random(System.currentTimeMillis());
        // Crée un générateur de nombres basé sur la date d'appel de la méthode
        Random random = new Random();
        // Nombre de messages, nombre de faces du dé
        long n = messages.length;
        // Tirage du dé à n faces
        long d = random.nextLong() % n;
        // Envoi du message correspondant
        return messages[(int)d];
      }
     
      // Exemples d'utilisations
      public static void main(String[] args) {
        // Tirage à pile ou face
        String[] on = {"Oui", "Non"};
        System.out.println(MiniOracle.say(on));
     
        // Alignements de D&D, création des alignements de personnages : méthode en croix
        String[] mnb = {"Mauvais", "Neutre", "Bon"};
        String[] lnc = {"Loyal", "Neutre", "Chaotique"};
        System.out.println(MiniOracle.say(lnc) + " " + MiniOracle.say(mnb));
     
        // Alignements de D&D, création des alignements de personnages : méthode en carré
        String[] ali = {"Loyal Mauvais", "Neutre Mauvais", "Chaotique Mauvais", "Loyal Neutre", "Neutre absolu", "Chaotique Neutre", "Loyal Bon", "Neutre Bon", "Chaotique Bon"};
        System.out.println(MiniOracle.say(ali));
     
        // Boucle infinie pour avoir le temps de lire le résultat
        while (true);
      }
     
    }
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

Discussions similaires

  1. Page Code Source, mettez vos codes ici
    Par Bovino dans le forum Contribuez
    Réponses: 8
    Dernier message: 05/12/2008, 13h11
  2. Participez à la FAQ VBA ou à la page Sources
    Par Nightfall dans le forum Contribuez
    Réponses: 1
    Dernier message: 04/08/2006, 18h34

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