2017-10-04 14 views
-1
public static printFnames(String sDir) { 
    Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println); 
} 

Étant donné quelque chose comme ci-dessus, ou en utilisant Apache IO ou Java NIO, comment puis-je regarder récursive pour le répertoire qui correspondent au schéma suivant:trouver récursive basé sur le modèle

COB03Oct2017 (qui ressemble à la dernière travail jour essentiellement)

J'ai une structure comme /sourcefolder/clientfolders/COB03Oct2017/file.pdf

Il y a beaucoup clientfolders et l'homme y COBddmmyyyy dossiers.

Disons que j'ai déjà une méthode qui me donne le nom du dossier cob.

Comment puis-je trouver tous les dossiers cob correspondants pour tous les dossiers clients?

@Test 
    public void testFiles() { 

     String sourcePath = "C:\\sourcepath\\"; 

     String cobPattern = "COB" + DateHelper.getPreviousWorkingDay(); 

     List<Path> clientDirectories = null; 

     try { 
      clientDirectories = Files.find(Paths.get(sourcePath), 1, 
        (path, bfa) -> bfa.isDirectory()) 
        .collect(Collectors.toList()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     List<Path> cobDirectories = getCobDirectories(clientDirectories, cobPattern); 

    } 

    private List<Path> getCobDirectories(List<Path> clientDirectories, String cobPattern) { 

     List<Path> collect = new ArrayList<>(); 

     clientDirectories 
       .stream() 
       .forEach(path -> { 
        try { 
        collect.addAll(Files.find(Paths.get(path.toString()), 1, 
           (p, bfa) -> bfa.isDirectory() 
             && p.getFileName().toString().equals(cobPattern)).collect(Collectors.toList())); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       }); 

     System.out.println("Done"); 
     return collect; 
    } 

Ce qui précède est ma tentative. Mais avec votre aide, je voudrais savoir si je fais quelque chose de mal, comment il peut être écrit mieux etc

Ce bit a également travaillé. Mais encore une fois cela peut-il être amélioré? Comment ne pas ignorer les exceptions telles AccessDenied

@Test 
    public void testFiles() { 

     String sourcePath = "\\\\server\\pathToCustomerReports\\"; 

     String cobPattern = "COB" + DateHelper.getPreviousWorkingDay(); 

     List<Path> clientDirectories = null; 

     try { 
      clientDirectories = Files.find(Paths.get(sourcePath), 1, 
        (path, bfa) -> bfa.isDirectory()) 
        .collect(Collectors.toList()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 


     List<Path> cobDirectories = new ArrayList<>(); 

     clientDirectories.forEach(path -> cobDirectories.addAll(getCobdirs(path))); 

     System.out.println("Done"); 


    } 

    private List<Path> getCobdirs(Path path) { 

     List<Path> cobDirs = new ArrayList<>(); 

     String cobPattern = "COB" + DateHelper.getPreviousWorkingDay(); 

     try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { 
      for (Path p : stream) { 
       if (path.toFile().isDirectory() && p.getFileName().toString().equals(cobPattern)) { 
        cobDirs.add(p); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return cobDirs; 
    } 
+0

Donc, dans cet exemple, vous voulez tous les dossiers 'COB03Oct2017' situés sous parent' sourcefolder' et différents 'clientfolders'? – procrastinator

+0

@procrastinator oui - d'abord obtenir tous les dossiers des clients sous la source, puis trouver des dossiers COB. Le but est de rechercher des fichiers uniquement dans le dernier dossier COB car j'ai affaire à un très gros répertoire. – user2781389

+0

Le code fourni fonctionne-t-il comme prévu? – c0der

Répondre

0
public List<File> getFilesToSend(String sourcePath, String pattern, String format) { 

    List<File> files = new ArrayList<>(); 

    File[] clientDirs = getCustomerDirs(sourcePath); 

    for (int i = 0; i < clientDirs.length; i++) { 
     files.addAll(processClientDirectory(clientDirs[i], pattern, format)); 
    } 

    return files; 
} 

private List<File> processClientDirectory(File clientDir, String pattern, String format) { 

    List<File> result = new ArrayList<>(); 

    pattern = pattern.toLowerCase(Locale.ENGLISH); 
    format = Constants.EXTENSION_SEPARATOR + format.toLowerCase(Locale.ENGLISH); 

    File cobDir = new File(clientDir, "COB" + DateHelper.getPreviousWorkingDay()); 
    getFilesToProcess(result, cobDir, pattern, format); 

    return result; 
} 

private void getFilesToProcess(List<File> result, File cobDir, String pattern, String format) { 


    if (!cobDir.exists()) { 
     return; 
    } 

    File[] files = cobDir.listFiles(pathName -> { 
     if (pathName.isDirectory()) { 
      return true; 
     } 

     if (!pathName.isFile()) { 
      return false; 
     } 

     String name = pathName.getName().toLowerCase(Locale.ENGLISH); 
     if (!name.startsWith(pattern)) { 
      return false; 
     } 
     if (!name.endsWith(format)) { 
      return false; 
     } 

     return true; 
    }); 

    for (int i = 0; i < files.length; i++) { 
     File current = files[i]; 
     if (current.isDirectory()) { 
      getFilesToProcess(result, current, pattern, format); 
      continue; 
     } 
     result.add(current); 
    } 
} 


private File[] getCustomerDirs(String sourcePath) { 
    File[] directories = new File(sourcePath).listFiles(File::isDirectory); 
    return directories; 
} 

Je les éléments suivants, mais il est un peu lent. Toute suggestion sur l'amélioration?

0

C'est ce que j'ai essayé de trouver le dossier spécifique dans votre sourcefolder. Je l'ai utilisé Java de file.fileList(filter)

public abstract class ChooseFile { 

public static File parent = new File("your/path/name"); 

public static void main(String args[]) throws IOException { 

    printFnames(parent.getAbsolutePath()); 
} 

public static void printFnames(String sDir) throws IOException { 

    // Take action only when parent is a directory 
    if (parent.isDirectory()) { 
     File[] children = parent.listFiles(new FileFilter() { 
      public boolean accept(File file) { 

       if (file.isDirectory() && file.getName().equalsIgnoreCase("YourString")) // I have serached for "bin" folders in my Source folder. 
        System.out.println(file.getAbsolutePath()); 
       else if (file.isDirectory()) 
        try { 
         parent = file; 
         printFnames(file.getAbsolutePath()); 
        } 
        catch (IOException exc) { 
         // TODO Auto-generated catch block 
         exc.printStackTrace(); 
        } 
       return file.isDirectory() || file.getName().toLowerCase().contains("YourString"); 
      } 
     }); 

     } 
    } 

} 

Cela retournerait tous les dossiers qui contient la chaîne "YourString" comme nom. Dans le cas, si vous voulez faire correspondre les noms avec regex alors vous devez changer la méthode .equalsIgnoreCase("YourString") à .matches("YourRegex"). Je pense que cela devrait fonctionner.

Cheers.

0

Une autre approche peut être une méthode récursive, qui creuser aussi profond que nécessaire pour trouver le dossier spécifié:

public static void main(String[] args) { 

    //the directory to search. It will search the whole tree 
    //so it should work also for sourcePath = "c:\\"; 
    String sourcePath = "c:\\sourcepath\\"; 
    String cobPattern = "COB03Oct2017"; 

    List<Path> cobDirectories = getCobDirectories(sourcePath, cobPattern); 
    cobDirectories.forEach(p -> System.out.println(p)); //check output 
} 

private static List<Path> getCobDirectories(String sourcePath, String cobPattern) { 
    List<Path> cobDirs = new ArrayList<>(); 
    getCobDirectories(sourcePath,cobPattern, cobDirs); 
    return cobDirs; 
} 

private static void getCobDirectories(String sourcePath, String cobPattern, List<Path> cobDirs) { 

    File file = new File(sourcePath); 

    if(! file.isDirectory()) {//search only in folders 
     return; 
    } 

    if(file.getName().equals(cobPattern)) {//add to collection 
     cobDirs.add(Paths.get(sourcePath)); 
     return; 
    } 

    if(file.list() == null) {//for abstract path or errors 
     return; 
    } 

    for (String fileName: file.list()){ 

     getCobDirectories((sourcePath+"\\"+fileName),cobPattern, cobDirs); 
    } 
}