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

EDT/SwingWorker Java Discussion :

[Swing & Threads] Ralentissements


Sujet :

EDT/SwingWorker Java

  1. #1
    Membre confirmé
    Inscrit en
    Juin 2009
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 100
    Par défaut [Swing & Threads] Ralentissements
    Bonjour à tous,

    J'ai un problème de compréhension. Je tourne en rond depuis quelques jours sur les threads, car mon application rame. Comment intégrer un swingworker à une IHM ?
    Je voudrais passer des paramètres à la méthode doInBackground() car
    dans cette méthode j'ai une fonction qui permet de mettre à jour ma JProgressBar mais qui a besoin de paramètre pour fonctionner. ( un Object)
    J'ai lu et relu ces documents :
    http://rom.developpez.com/java-swingworker/
    http://gfx.developpez.com/tutoriel/j...ing-threading/
    et je ne comprends toujours pas comment m'en sortir.
    Car avant d'essayer de mettre en place le swingworker, j'avais fait un mécanisme de thread pour le setValue de la JProgressBar avec une variable static.
    Ma classe traitemement avait un public static JPanel getProgressBarFTP (),
    et dans mon IHM j'ai mi

    add(getProgressBarFTP());
    le résultat ça fonctionne, mais ça rame.. Help !




    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
    package Moteur;
    import java.io.*;
    import java.net.SocketException;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    //import org.apache.commons.net.PrintCommandListener;
     
    import org.apache.commons.net.ftp.*;
     
    public class Ftp extends FTPClient
    {
    	static JProgressBar progressBar;
    	static JLabel labelVitesse;
    	static JLabel labelNomFichier;
     
    	static JPanel pane;
    	static boolean error;
    	static boolean Tx;
     
    	public static int vitesse , taux;
     
    	public static String nomFichier;
     
     
    	/**
             * @return the nomFichier
             */
    	public static String getNomFichier() {
    		return nomFichier;
    	}
     
    	/**
             * @return the vitesse
             */
    	public static int getVitesse() {
    		return vitesse;
    	}
     
    	/**
             * @return the taux
             */
    	public static int getTaux() {
    		return taux;
    	}
     
    	public Ftp()
    	{
     
    	}
     
    	public static JPanel getProgressBarFTP ()
    	{
    		pane = new JPanel();
    		labelNomFichier = new JLabel();
    		pane.add(labelNomFichier);
    		labelVitesse = new JLabel("0 Ko/s");
    		pane.add(labelVitesse);
    		//Where the GUI is constructed:
    		progressBar = new JProgressBar(0, 100);
    		pane.updateUI();
     
    		ReloadBar();
    		return pane;
     
    	}
     
    	public static void ReloadBar(){
     
    		threadProgress my = new Moteur.Ftp.threadProgress();
    		my.end = false;
    		my.start();
     
    		progressBar.setValue(0);
    		progressBar.setStringPainted(true);
     
    		pane.add(progressBar);
     
    	}
    	private static class threadProgress extends Thread{
    		boolean end = false;
     
    		public void run() {
    			while(!end){
    			final int taux = Ftp.getTaux();
    			if(!error){			//Si pas d'erreur
     
     
    				Runnable setValue = new Runnable() {
    				    public void run() {
    				        progressBar.setValue(taux);
    				    }
    				};
    				SwingUtilities.invokeLater(setValue);
    				labelNomFichier.setText(Ftp.getNomFichier());
    				//progressBar.setValue(taux);
    				labelVitesse.setText(Integer.toString(Ftp.getVitesse())
    							+ "Ko/s");
     
    				//Ftp.pane.updateUI();
    				//System.err.println(f.getTaux());
    				//progressBar.setStringPainted(true);
    				if(taux == 100 && Tx){
    					System.out.println("FIN");
    					this.end();
    					labelVitesse.setText("Transfert OK");
    					}
     
    				}
     
    			else{
    				System.err.println("FIN du thread");
    				this.end();
    				//Ftp.pane.updateUI();
    				labelVitesse.setText("Transfert ERREUR");
     
    				}
    			/*
    			try {
    				this.sleep(5000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				//e.printStackTrace();
    				System.err.println("Rafraichissement thread JProgressBar");
    			}*/
    			}
    		}
    		public void end(){
    			this.end = true;
    			Ftp.pane.remove(progressBar);
    			taux = 0;
    			Ftp.pane.updateUI();
    			progressBar.setValue(0);
     
    		}
    	}
     
     
       	public static boolean Upload(String server, String username, String password, String remote, String local)
        {
       		FTPClient f = new FTPClient();
     
     
       		nomFichier = remote;
    		error = false;
            Tx = false;   
            ReloadBar();
     
            //this.addProtocolCommandListener(new PrintCommandListener( new PrintWriter(System.out))); //Active les écoutes des commandes FTP
     
            try
            {
     
               f.connect(server);
                //System.out.println("Connected to " + server + ".");
     
                int reply = f.getReplyCode();
     
                if (!FTPReply.isPositiveCompletion(reply))
                {
                    f.disconnect();
                    System.err.println("Connexion refusée.");             
                }
            }
            catch (IOException e)
            {
                if (f.isConnected())
                {
                    try
                    {
                        f.disconnect();
                    }
                    catch (IOException g)
                    {
                        // do nothing
                    }
                }
                System.err.println("Impossible de joindre le serveur.");
                //e.printStackTrace();
            }
     
            try
            {
     
     
                if (!f.login(username, password))
                {
                    f.logout();
                    error = true;
                    System.out.println("Login ou mot de passe non valide");
                }
     
                //System.out.println("Remote system is " + this.getSystemName());
     
                f.setFileType(FTP.BINARY_FILE_TYPE);
     
                f.enterLocalPassiveMode();
     
                File fichier = new File(local);
     
                InputStream fis = new FileInputStream(fichier);
                OutputStream os = f.storeFileStream(remote);
     
     
                byte buf[] = new byte[f.getBufferSize()];
                int taille=0;
                long total = 0;
                int bytesRead = fis.read(buf);
                long temps_debut = System.currentTimeMillis();
                long temps_fin = System.currentTimeMillis();
                vitesse = 0;
                taux = 0;
     
                while ((taille = bytesRead) != -1) {
                	total+= taille;
                    try {
    					os.write(buf, 0, bytesRead);
    				} catch (Exception e1) {
    					// TODO Auto-generated catch block
    					error = true;  // Signal l'erreur de transfert de fichier
     
    				}
                    bytesRead = fis.read(buf);
                    //System.out.println(" " + total);
                    temps_fin = System.currentTimeMillis();
                    taux =  (int) ((int) total * 100 / fichier.length()) ;
     
                    try {
    					vitesse = (int) (( total * 1000 / 1024 ) /  ( temps_fin - temps_debut ));
    				} catch (Exception e) {
    					// TODO Auto-generated catch block
    					//e.printStackTrace();
    				}
    				//System.out.println("Vitesse : " + vitesse);
    				//System.out.println("taux " + taux );
                }
                fis.close();
                try {
    				os.flush();
    				os.close();
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				//e.printStackTrace();
    			}
     
     
                if(f.completePendingCommand()){
                	System.out.println("Transfert completed. ");
                	Tx = true;
                }
     
              /*
                InputStream is = new FileInputStream(local);  
                OutputStream os = this.storeFileStream( remote );
                byte[] buffer = new byte[1024];  
                long total = 0;
                int taille_lue = 0;
                long temps_debut = System.currentTimeMillis();
                long temps_fin = temps_debut;
                long speed = 0;
               
                while( ( taille_lue = is.read( buffer ) ) > 0 )  
                {
                  System.out.println("Taille " + taille_lue);
                  total += taille_lue;
                  os.write( buffer, 0, taille_lue );
                  temps_fin = System.currentTimeMillis();
                  speed = total / ( ( temps_fin - temps_debut ) / 1000 );
                }
               
                os.flush();
                is.close();
                os.close();
                
                */
     
               // this.storeFile(remote, input);
     
               // input.close();
     
                f.logout();
            }
            catch (FTPConnectionClosedException e)
            {
                error = true;
                System.err.println("Server closed connection.");
                //e.printStackTrace();
            }
            catch (IOException e)
            {
                error = true;
                //e.printStackTrace();
            }
            finally
            {
                if (f.isConnected())
                {
                    try
                    {
                        f.disconnect();
                    }
                    catch (IOException e){}
                }
            }
            if(error)System.err.println("C'est la crotte");
         return error;
        }
     
       	public boolean TestConnexion(String server) throws SocketException, IOException			//Test si le serveur est joignable
       	{
       		boolean error = false;
     
            this.connect(server);
            int reply = this.getReplyCode();  
            if (FTPReply.isPositiveCompletion(reply))
                {
                    this.disconnect();
                    System.err.println("Connexion refusée.");             
                }
     
            return error;
       	}
        public static void main(String[] args) {
     
     
        	for (UIManager.LookAndFeelInfo laf :
        		UIManager.getInstalledLookAndFeels() ){
        		if ("Nimbus".equals(laf.getName())) {
        		try {
        		UIManager.setLookAndFeel(laf.getClassName());
        		} catch (Exception e) {
        		// TODO: handle exception
        		}
     
        		}
        		}
     
     
     
        	JFrame frame = new JFrame();
        	frame.add(Ftp.getProgressBarFTP());
        	frame.setVisible(true);
        	frame.setSize(400, 400);
     
     
    			if(Ftp.Upload("127.0.0.1", "FTPPLS", "pls91fr", "yaya.jpg", "C:\\moteurFTP\\archive\\vrai\\TEST_20100303141929.jpg")){
    				System.out.println("error dude");
    			}
     
        }
     
    }

  2. #2
    Membre émérite Avatar de Heimdal
    Profil pro
    Inscrit en
    Avril 2006
    Messages
    549
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2006
    Messages : 549
    Par défaut
    Passer les paramètres en arguments de ton constructeur.?

  3. #3
    Membre confirmé
    Inscrit en
    Juin 2009
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 100
    Par défaut
    ba en gros ce que je voudrais c'est excuter un swingworker en lui passant des paramère tel que le nom du serveur login mdp fichier à uploader etc...

    et dans mon ihm ajouter le panel qui contient la barre de progression.

    Franchement ça commence à me {{{# !!

  4. #4
    Membre confirmé
    Inscrit en
    Juin 2009
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 100
    Par défaut
    à tête reposé, j'ai réussi à trouver mes erreurs. Dans ma classe j'utilisais abondamment l' updateUI(), donc ça ramait.
    Je les ai mieux placé et ça va mieux..
    Merci quand même

  5. #5
    Expert confirmé
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Par défaut
    Logiquement il n'y a jamais besoin d'appeler UpdateUI. Repaint (pour la partie juste graphique) et revalidate(pour le coté layout) suffisent amplement a moins que tu ais des trucs vraiment mal foutus dans ton code.

  6. #6
    Expert éminent
    Avatar de adiGuba
    Homme Profil pro
    Développeur Java/Web
    Inscrit en
    Avril 2002
    Messages
    13 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java/Web
    Secteur : Transports

    Informations forums :
    Inscription : Avril 2002
    Messages : 13 938
    Billets dans le blog
    1
    Par défaut
    Salut,

    A quoi sert ton thread threadProgress ????
    Apparemment elle fait une boucle active qui doit te bouffer 100% du CPU

    Sinon je n'ai pas vu l'utilisation du SwingWorker dans ton code


    a++

  7. #7
    Membre confirmé
    Inscrit en
    Juin 2009
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 100
    Par défaut
    Effectivement il n'y a pas de swing worker, car justement je ne pouvais pas utiliser ma classe FTP comme je voulais après.

    Le threadProgress il me permet d'actualiser la nouvelle valeur de progression du transfert. Oui ça doit bouffer beaucoup de perf. Tu sais comment réduire ça ?
    ( à part un sleep ? )

  8. #8
    Expert éminent
    Avatar de adiGuba
    Homme Profil pro
    Développeur Java/Web
    Inscrit en
    Avril 2002
    Messages
    13 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java/Web
    Secteur : Transports

    Informations forums :
    Inscription : Avril 2002
    Messages : 13 938
    Billets dans le blog
    1
    Par défaut
    Ben justement en utilisant un SwingWorker...

    Maintenant j'ai du mal à comprendre ton code puisque ton thread ne fait aucun traitement particulier, si ce n'est de modifier constamment ton interface graphique. Sans compter que tout ceci devrait être fait dans l'EDT et non pas dans un thread à part...


    a++

  9. #9
    Membre confirmé
    Inscrit en
    Juin 2009
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 100
    Par défaut
    oui mais c'est ça le truc, je ne comprends pas comment mettre ma classe Ftp dans un swing worker.
    car comment je peux passer en paramètre le server login fichier etc.. ?

    Pour executer une méthode dans l'EDT il faut juste faire un invokelater ?

  10. #10
    Membre confirmé
    Inscrit en
    Juin 2009
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 100
    Par défaut
    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
    package Moteur;
    import java.io.*;
    import java.net.SocketException;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    //import org.apache.commons.net.PrintCommandListener;
     
    import org.apache.commons.net.ftp.*;
     
    public class Ftp extends FTPClient
    {
    	static JProgressBar progressBar;
    	static JLabel labelVitesse;
    	static JLabel labelNomFichier;
     
    	static JPanel pane;
    	static boolean error;
    	static boolean Tx;
     
    	public static int vitesse , taux;
     
    	public static String nomFichier;
     
     
    	/**
             * @return the nomFichier
             */
    	public static String getNomFichier() {
    		return nomFichier;
    	}
     
    	/**
             * @return the vitesse
             */
    	public static int getVitesse() {
    		return vitesse;
    	}
     
    	/**
             * @return the taux
             */
    	public static int getTaux() {
    		return taux;
    	}
     
    	public Ftp()
    	{
     
    	}
     
    	public static JPanel getProgressBarFTP ()
    	{
    		pane = new JPanel();
    		labelNomFichier = new JLabel();
    		pane.add(labelNomFichier);
    		labelVitesse = new JLabel("0 Ko/s");
    		pane.add(labelVitesse);
    		//Where the GUI is constructed:
    		progressBar = new JProgressBar(0, 100);
     
     
    		return pane;
     
    	}
     
    	public static void ReloadBar(){
     
    		progressBar.setValue(0);
    		progressBar.setStringPainted(true);
     
    		pane.add(progressBar);
    		pane.repaint();
    	}
     
     
    	public static void setTaux(int taux){
    		if(!error){			//Si pas d'erreur
     
    	        if(taux != 0 )progressBar.setValue(taux);
    	        labelNomFichier.setText(Ftp.getNomFichier());
     
    	        labelVitesse.setText(Integer.toString(Ftp.getVitesse())
    				+ "Ko/s");
     
     
    	 if(taux == 100 && Tx){
    				System.out.println("FIN");
    				end();
    				labelVitesse.setText("Transfert OK");
    				}
    	}
     
    else{
    	System.err.println("FIN du thread");
    	end();
    	labelVitesse.setText("Transfert ERREUR");
     
    	}
     
    	}
    	public static void end(){
    		Ftp.pane.remove(progressBar);
    		taux = 0;
    		Ftp.pane.repaint();
    		progressBar.setValue(0);
     
    	}
     
     
     
       	public static boolean Upload(String server, String username, String password, String remote, String local)
        {
       		FTPClient f = new FTPClient();
     
     
       		nomFichier = remote;
    		error = false;
            Tx = false;   
            ReloadBar();
     
            //this.addProtocolCommandListener(new PrintCommandListener( new PrintWriter(System.out))); //Active les écoutes des commandes FTP
     
            try
            {
     
               f.connect(server);
                //System.out.println("Connected to " + server + ".");
     
                int reply = f.getReplyCode();
     
                if (!FTPReply.isPositiveCompletion(reply))
                {
                    f.disconnect();
                    System.err.println("Connexion refusée.");             
                }
            }
            catch (IOException e)
            {
                if (f.isConnected())
                {
                    try
                    {
                        f.disconnect();
                    }
                    catch (IOException g)
                    {
                        // do nothing
                    }
                }
                System.err.println("Impossible de joindre le serveur.");
                //e.printStackTrace();
            }
     
            try
            {
     
     
                if (!f.login(username, password))
                {
                    f.logout();
                    error = true;
                    System.out.println("Login ou mot de passe non valide");
                }
     
                //System.out.println("Remote system is " + this.getSystemName());
     
                f.setFileType(FTP.BINARY_FILE_TYPE);
     
                f.enterLocalPassiveMode();
     
                File fichier = new File(local);
     
                InputStream fis = new FileInputStream(fichier);
                OutputStream os = f.storeFileStream(remote);
     
     
                byte buf[] = new byte[f.getBufferSize()];
                int taille=0;
                long total = 0;
                int bytesRead = fis.read(buf);
                long temps_debut = System.currentTimeMillis();
                long temps_fin = System.currentTimeMillis();
                vitesse = 0;
                taux = 0;
     
                while ((taille = bytesRead) != -1) {
                	total+= taille;
                    try {
    					os.write(buf, 0, bytesRead);
    				} catch (Exception e1) {
    					// TODO Auto-generated catch block
    					error = true;  // Signal l'erreur de transfert de fichier
     
    				}
                    bytesRead = fis.read(buf);
                    //System.out.println(" " + total);
                    temps_fin = System.currentTimeMillis();
                    taux =  (int) ((int) total * 100 / fichier.length()) ;
                    setTaux(taux);
     
                    try {
    					vitesse = (int) (( total * 1000 / 1024 ) /  ( temps_fin - temps_debut ));
    				} catch (Exception e) {
    					// TODO Auto-generated catch block
    					//e.printStackTrace();
    				}
    				//System.out.println("Vitesse : " + vitesse);
    				//System.out.println("taux " + taux );
                }
                fis.close();
                try {
    				os.flush();
    				os.close();
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				//e.printStackTrace();
    			}
     
     
                if(f.completePendingCommand()){
                	System.out.println("Transfert completed. ");
                	Tx = true;
                }
     
              /*
                InputStream is = new FileInputStream(local);  
                OutputStream os = this.storeFileStream( remote );
                byte[] buffer = new byte[1024];  
                long total = 0;
                int taille_lue = 0;
                long temps_debut = System.currentTimeMillis();
                long temps_fin = temps_debut;
                long speed = 0;
               
                while( ( taille_lue = is.read( buffer ) ) > 0 )  
                {
                  System.out.println("Taille " + taille_lue);
                  total += taille_lue;
                  os.write( buffer, 0, taille_lue );
                  temps_fin = System.currentTimeMillis();
                  speed = total / ( ( temps_fin - temps_debut ) / 1000 );
                }
               
                os.flush();
                is.close();
                os.close();
                
                */
     
               // this.storeFile(remote, input);
     
               // input.close();
     
                f.logout();
            }
            catch (FTPConnectionClosedException e)
            {
                error = true;
                System.err.println("Server closed connection.");
                //e.printStackTrace();
            }
            catch (IOException e)
            {
                error = true;
                //e.printStackTrace();
            }
            finally
            {
                if (f.isConnected())
                {
                    try
                    {
                        f.disconnect();
                    }
                    catch (IOException e){}
                }
            }
            if(error)System.err.println("C'est la crotte");
         return error;
        }
     
       	public boolean TestConnexion(String server) throws SocketException, IOException			//Test si le serveur est joignable
       	{
       		boolean error = false;
     
            this.connect(server);
            int reply = this.getReplyCode();  
            if (FTPReply.isPositiveCompletion(reply))
                {
                    this.disconnect();
                    System.err.println("Connexion refusée.");             
                }
     
            return error;
       	}
        public static void main(String[] args) {
     
     
        	for (UIManager.LookAndFeelInfo laf :
        		UIManager.getInstalledLookAndFeels() ){
        		if ("Nimbus".equals(laf.getName())) {
        		try {
        		UIManager.setLookAndFeel(laf.getClassName());
        		} catch (Exception e) {
        		// TODO: handle exception
        		}
     
        		}
        		}
     
     
     
        	JFrame frame = new JFrame();
        	frame.add(Ftp.getProgressBarFTP());
        	frame.setVisible(true);
        	frame.setSize(400, 400);
     
     
    			if(Ftp.Upload("127.0.0.1", "FTPPLS", "pls91fr", "yaya.jpg", "C:\\paletsystem\\moteurFTP\\archive\\vrai\\AP1450_20100303141929.jpg")){
    				System.out.println("error dude");
    			}
    			System.out.println("fichier 1");
    			if(Ftp.Upload("127.0.0.1", "FTPPLS", "pls91fr", "yaza.jpg", "C:\\paletsystem\\moteurFTP\\archive\\vrai\\AP1450_20100303141929.jpg")){
    				System.out.println("error dude");
    			}
        }
     
    }
     
     
    /*
    package Moteur;
    import java.io.*;
    import java.net.SocketException;
     
    import javax.swing.JFrame;
     
    //import org.apache.commons.net.PrintCommandListener;
    import org.apache.commons.net.ftp.*;
     
     
     
    public class Ftp extends FTPClient
    {
     
    	public Ftp()
    	{
     
    	}
     
       	public boolean Upload(String server, String username, String password, String remote, String local) throws IOException
        {
        
    		boolean error = false;
                
           
            //this.addProtocolCommandListener(new PrintCommandListener( new PrintWriter(System.out))); //Active les écoutes des commandes FTP
            
            try
            {
                
                this.connect(server);
                //System.out.println("Connected to " + server + ".");
                
                int reply = this.getReplyCode();
                
                if (!FTPReply.isPositiveCompletion(reply))
                {
                    this.disconnect();
                    System.err.println("Connexion refusée.");             
                }
            }
            catch (IOException e)
            {
                if (this.isConnected())
                {
                    try
                    {
                        this.disconnect();
                    }
                    catch (IOException f)
                    {
                        // do nothing
                    }
                }
                System.err.println("Impossible de joindre le serveur.");
                //e.printStackTrace();
            }
     
            try
            {
            	
            	
                if (!this.login(username, password))
                {
                    this.logout();
                    error = true;
                    System.err.println("Login ou mot de passe non valide");
                }
     
                //System.out.println("Remote system is " + this.getSystemName());
                
                this.setFileType(FTP.BINARY_FILE_TYPE);
                
                this.enterLocalPassiveMode();
     
     
                InputStream input;
     
                input = new FileInputStream(local);
     
                if(!this.storeFile(remote, input))
                {
                	error=true;
                	System.err.println("ERREUR D'ENVOI DE FICHIER");
                }
                input.close();
      
                this.logout();
            }
            catch (FTPConnectionClosedException e)
            {
                error = true;
                System.err.println("Server closed connection.");
                //e.printStackTrace();
            }
            catch (IOException e)
            {
                error = true;
                //e.printStackTrace();
                System.err.println(e.getMessage());
            }
            finally
            {
                if (this.isConnected())
                {
                    try
                    {
                        this.disconnect();
                    }
                    catch (IOException f){}
                }
            }
     
            
         return error;
        }
       	
       	static public boolean TestConnexion(String server) throws SocketException, IOException			//Test si le serveur est joignable
       	{
       		FTPClient ftp = new FTPClient();
       		boolean error = false;
       		//ftp.setDefaultTimeout(2 * 1000);
     
            ftp.connect(server);
            int reply = ftp.getReplyCode();  
            if (FTPReply.isPositiveCompletion(reply))
                {
                    ftp.disconnect();
                    error = true;
                }
             
            return error;
       	}
       	
       	public static void main(String[] args) {
        	Ftp f = new Ftp();
        	JFrame frame = new JFrame();
        	//frame.add(Ftp.getProgressBarFTP());
        	frame.setVisible(true);
        	try {
    			f.Upload("127.0.0.1", "FTPPLS", "pls91fr", "yaya.jpg", "C:\\paletsystem\\moteurFTP\\archive\\vrai\\AP1450_20100303141929.jpg");
    			} 
        	catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    			}
               
        }
       	
       	
    }
     
    */

    Ici j'ai viré le thread qui servait à rien effectivement, car l'appel d'une méthode fait la même chose.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Toujours Swing et Thread
    Par Patrice Henrio dans le forum EDT/SwingWorker
    Réponses: 18
    Dernier message: 14/02/2013, 23h13
  2. [Swing et multi Thread] Ralentissements étranges
    Par lemmingou2010 dans le forum EDT/SwingWorker
    Réponses: 10
    Dernier message: 13/03/2010, 18h58
  3. [Freeze Swing et Threads] Freeze lors d'un appel
    Par Tuxico dans le forum EDT/SwingWorker
    Réponses: 1
    Dernier message: 02/11/2008, 16h53
  4. Problème SWING et Threads
    Par CamilleH dans le forum AWT/Swing
    Réponses: 14
    Dernier message: 12/06/2008, 12h19
  5. Swing et thread
    Par trax44 dans le forum EDT/SwingWorker
    Réponses: 37
    Dernier message: 22/06/2006, 13h10

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