Last active
October 20, 2020 17:13
-
-
Save GaetanoPiazzolla/755613db68494b3ea5943955c67f3900 to your computer and use it in GitHub Desktop.
Recursive Camel Insensitive Java File Discovery ( Java 1.8 )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.Arrays; | |
import java.util.HashSet; | |
import java.util.List; | |
import java.util.Set; | |
import java.util.stream.Collectors; | |
import java.util.stream.StreamSupport; | |
public class CamelInsensitivePath { | |
public static void main(final String[] args) { | |
Set<String> result = returnFilesInsideCamelInsensitiveDirectoryPath("C:\\test\\", "test2\\tEsT"); | |
System.out.println(result); | |
} | |
private static Set<String> returnFilesInsideCamelInsensitiveDirectoryPath(String basePath, String path) { | |
Set<String> filePath = new HashSet<>(); | |
if (path == null || path.isEmpty() || basePath == null || basePath.isEmpty()) { | |
return filePath; | |
} | |
List<String> pieces = splitPath(path); | |
if (pieces.isEmpty()) { | |
return filePath; | |
} | |
Set<String> directories = new HashSet<>(); | |
recursiveSearch(basePath, pieces, directories); | |
for (String dir : directories) { | |
File startingDirectory = new File(dir); | |
String[] list = startingDirectory.list(); | |
filePath.addAll(Arrays.stream(list).map(s -> dir + File.separator + s).collect(Collectors.toSet())); | |
} | |
return filePath; | |
} | |
private static List<String> splitPath(String pathString) { | |
Path path = Paths.get(pathString); | |
return StreamSupport.stream(path.spliterator(), false).map(Path::toString) | |
.collect(Collectors.toList()); | |
} | |
private static void recursiveSearch(String basePath, List<String> pieces, Set<String> directories) { | |
File startingDirectory = new File(basePath); | |
String[] list = startingDirectory.list( | |
(dir, name) -> name.equalsIgnoreCase(pieces.get(0))); | |
Set<String> results = Arrays.stream(list).map(s -> basePath + File.separator + s).collect(Collectors.toSet()); | |
pieces.remove(0); | |
if (pieces.isEmpty()) { | |
directories.addAll(results); | |
return; | |
} | |
for (String s : results) { | |
recursiveSearch(s, pieces, directories); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment