Recently I had to compare the contents of two directories on Windows.
Since I was not allowed to install new software on the machine and the workaround of using windows shell commands in combination with Excel and Regular Expressions was a bit annoying I deceided to implement a class in Java.
Source Code for comparing directories
Below a class, which is able to use a given regular expressions to compare file names in two given directories.
The concept is as follows.
- Create a new object of this class providing the following parameters.
- dirPath - a path for a directory, which should be used as the source for comparisons.
- pattern - a Pattern object for identifying files of interest. A files name has to match the pattern.
- fileExtension - a file extension, which should be used as filter for file types of interest.
- Call method compareDir providing the target directory you want to compare against the source directory provided via construtors parameters.
- The returned collection contains all file names, which ...
- ... match the given pattern object ...
- ... and are in the source directory ...
- ... but are not in given target directory.
- The returned Set contains the key strings, which can be used for the HashMaps returned by the methods for getting the target and source file names and file paths.
If you are interested in the files, which are in synch / common between two directories use the method getCommonFileNames.
In the end I only compare two collections, which is very easy using HashSets. Not only can I use key Strings, but also the class already provides a method called removeAll. What would have required coding is already free to use :0). I like Java a lot for this reason.
ret = new HashSet<String>(srcFiles.keySet());
And here the full source code.
Below you can find a small class I used for unit testing on the above class for example usage.