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

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

Java Discussion :

Java Watch Service Api Problème


Sujet :

Java

  1. #1
    Membre habitué
    Homme Profil pro
    qsf
    Inscrit en
    Juillet 2012
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Albanie

    Informations professionnelles :
    Activité : qsf
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Juillet 2012
    Messages : 5
    Par défaut Java Watch Service Api Problème
    Bonjour ,
    Je suis en train d'utiliser l'api watch service de java pour se mettre à l’écoute sur un lecteur réseau , mais ce dernier ne fonctionne pas sur les dossiers que je les ai pas créer moi même et sur les raccourcis (il n' y a pas des messages d'erreur affichés , juste il reste à l’écoute et ne capte pas l' Evénement ) .
    Aide SVP.

    Voila le Code :


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
     
    package org.test;
    import java.net.SocketException;
     
    import java.nio.file.*;
    import org.apache.commons.net.ftp.FTPClient;
    import java.nio.file.FileSystem;
    import static java.nio.file.StandardWatchEventKinds.*;
    import static java.nio.file.LinkOption.*;
    import java.nio.file.attribute.*;
    import java.io.*;
    import java.util.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import static java.nio.file.StandardCopyOption.*;
    import static java.nio.file.StandardCopyOption.*;
    public class WatchDir {
        private final WatchService watcher;
        private final Map<WatchKey,Path> keys;
        private final boolean recursive;
        private boolean trace = false;
        FTPClient client;
        FileInputStream fis;
        @SuppressWarnings("unchecked")
        static <T> WatchEvent<T> cast(WatchEvent<?> event) {
            return (WatchEvent<T>)event;
                                                           }
    //********************************************************************************************************************************************
        private void register(Path dir) throws IOException {
            WatchKey key = dir.register(watcher, ENTRY_CREATE);
            if (trace) {
                Path prev = keys.get(key);
                if (prev == null) {
                    System.out.format("register: %s\n", dir);
                } else {
                    if (!dir.equals(prev)) {
                        System.out.format("update: %s -> %s\n", prev, dir);
                    }
                }
            }
            keys.put(key, dir);
                                                           }
     //********************************************************************************************************************************************
        private void registerAll(final Path start) throws IOException {
            Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException
                {
                    register(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
                                                                      }
    //********************************************************************************************************************************************
        WatchDir(Path dir, boolean recursive) throws IOException {
            this.watcher = FileSystems.getDefault().newWatchService();
            this.keys = new HashMap<WatchKey,Path>();
            this.recursive = recursive;
         client = new FTPClient();
       client.connect("***.***.***.***");
        client.login("wejdi.gharibi","gharibi***");
        fis = null;
            if (recursive) {
                System.out.format("Scanning %s ...\n", dir);
                registerAll(dir);
                System.out.println("Done.");
            } else {
                register(dir);
            }
     
            this.trace = true;
                                                                 }
    //********************************************************************************************************************************************
        String fichier(String a,String b,char c )
        {
        	 int d;
        	 String ch="";
        	 File repertoire = new File(a);
             File[] fichiers = repertoire.listFiles();
             for(File fichier : fichiers)
             { 
               if (fichier.getName().startsWith(b)) {
            	   d=fichier.getName().lastIndexOf('.');
            	   if(fichier.getName().charAt(d-1)==c){
     
                  ch= fichier.getName().toString();
            	   }
               }
             }
    		return ch;
        }
      //********************************************************************************************************************************************
     
        void Transfert (String ch , String ch1) {
        	 try {
                 fis = new FileInputStream(ch);
                 client.storeFile(ch1, fis);
                 fis.close();
             } catch (SocketException ex) {
                 Logger.getLogger(WatchDir.class.getName()).log(Level.SEVERE, null, ex);
             } catch (IOException ex) {
                 Logger.getLogger(WatchDir.class.getName()).log(Level.SEVERE, null, ex);
             }
     
                                                }
    //********************************************************************************************************************************************
        char precident (char ch){
        	char [] a1 =new char[] { '-','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        	char ch1='-';
        	for ( int i =0;i<a1.length;i++){
        		      if (a1[i]==ch)
        			               {
        			                ch1=a1[i-1];
        			               }		
        	                               } 	
    		return ch1;	
        }
    //********************************************************************************************************************************************
        void processEvents() throws IOException {
        	FileSystem fs = FileSystems.getDefault();
            while(true) {
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException x) {
                    return;
                }
                Path dir = keys.get(key);
                if (dir == null) {
                    System.err.println("WatchKey not recognized!!");
                    continue;
                }
                for (WatchEvent<?> event: key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();
                    if (kind == OVERFLOW) {
                        continue;
                    }
                    WatchEvent<Path> ev = cast(event);
                    Path name = ev.context();
                    Path child = dir.resolve(name);
    //**************************************************************************************************************************************************
                 //System.out.format("%s: %s\n", event.kind().name(), child);
           Path PathTemp = ev.context();
           File FileChange = new File(PathTemp.toAbsolutePath().toString());
           Path path = fs.getPath(key.watchable().toString(), event.context().toString());
           int c=FileChange.getName().lastIndexOf('.');
           if(c!=(-1) &&!FileChange.getName().equalsIgnoreCase("Thumbs.db") && FileChange.getName().charAt(c-1)>= 'A' &&FileChange.getName().charAt(c-1)<='Z')
                	                       {
        	        int ind=FileChange.getName().indexOf("_");
        	        String seq=FileChange.getName().substring(0, ind);
                    char d=FileChange.getName().charAt(c-1);
                    String fh=path.toString().substring(0,  path.toString().lastIndexOf("\\"));
                    System.out.println("a"+fh);
                    String nom=fichier(fh,seq,precident(d)) ;
     
                 //  System.out.println(d);
                 //  System.out.println(precident(d));
                    String ch4=FileChange.getName().replace(d+".", precident(d)+".");
                 //Path path1 = fs.getPath("\\\\***.***.***.***\\tmp\\wajdi\\"+ch4);
                    String dh1=path.toString().replace(FileChange.getName(),nom);
     
                    Path path2 = fs.getPath(dh1);
                    System.out.println("La nouvelle valeur de la chaine est : "+ch4+"\n le path est :"+dh1);
                   // Transfert (dh1,ch4);
                   try {
                        Files.delete(path2);
     
                    } catch (NoSuchFileException x) {
                        System.err.format("%s: no such" + " file or directory%n", path2);
                    } catch (DirectoryNotEmptyException x) {
                        System.err.format("%s not empty%n", path2);
                    } catch (IOException x) {
                        // File permission problems are caught here.
                        System.err.println(x);
                    }
                	                       }
                //Files.move(path2, path1,REPLACE_EXISTING);
    //**********************************************************************************************************************************************
                    if (recursive && (kind == ENTRY_CREATE)) {
                        try {
                            if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                                registerAll(child);
                            }
                        } catch (IOException x) {
                            // ignore to keep sample readbale
                        }
                    }
                }
     
                boolean valid = key.reset();
                if (!valid) {
                    keys.remove(key);
     
                    if (keys.isEmpty()) {
                        break;
                    }
                }
            }
            client.logout();
        }
     
     
        public static void main(String[] args) throws IOException {
            boolean  recursive = true;
            Path dir = Paths.get("C:\\Users\\wejdi.gharibi\\Desktop\\SS");
            new WatchDir(dir, recursive).processEvents();
     
        }
    }

  2. #2
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2012
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2012
    Messages : 36
    Par défaut
    J'ai le même problème l api fonctionne sur un lecteur réseau (sur un dossier que je l'ai créer) et ne fonctionne pas sur l'autre lecteur , j'ai même créer un raccourcis de ce dossier trouvant sur le lecteur , mais il ne fonctionne pas aussi

Discussions similaires

  1. API Java Web Service
    Par jowelle dans le forum Services Web
    Réponses: 1
    Dernier message: 26/06/2013, 15h14
  2. Java watch service problème
    Par yahya.romdhane.ensi dans le forum Général Java
    Réponses: 5
    Dernier message: 22/03/2013, 09h54
  3. Réponses: 1
    Dernier message: 03/03/2009, 11h09
  4. [Débutant][Java] Web Service
    Par ArseNic dans le forum XML/XSL et SOAP
    Réponses: 1
    Dernier message: 14/11/2005, 11h09
  5. [C#][service windows] problème de débutant avec 1 timer
    Par Nycos62 dans le forum Windows Forms
    Réponses: 3
    Dernier message: 14/10/2005, 11h22

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