This lab focuses on file paths and manipulating directory structures.
Oracle Java Tutorial links
- Use the Path class to operate on file and directory paths.
- Use the Files class to check, delete, copy, or move a file or directory.
- Read and change file and directory attributes.
- Recursively access a directory tree.
- Find a file by using the PathMatcher class.
- Watch a directory for changes by using WatchService.
If you have not already done so in the lab on I/O Fundamentals, do the exercises for I/O in the Oracle Java tutorial here. Once you are done, the answers can be checked here.
In this exercise you will create a tool which, given two directories, will recursively compare the contents of those directories, and return lists of files which are in one directory but not the other. You will use File, Path, and FileVisitor classes, among others.
Create a class CompareDirectories in the package io with the following method:
public static List<Path>[] compareDirectories(Path oldDir, Path newDir) throws IOException
This method takes two directories oldDir and newDir. It will recursively scan all the files and returns an array of two lists. The first list contains all the files in oldDir only, and the second list contains all the files in newDir only. Each of the Paths in these result lists will be relative to their respective directory. For example if oldDir is '/a/b', and the result list contains the file '/a/b/c/d', then the list will return that path as 'c/d'.
An automated test has been created for this exercise: CompareDirectoriesTest.java.
As an extension, try modifying the method to return a third list, containing a list of all files in both oldDir and newDir, but which have been modified. Use the file length and file attributes to determine if the file has been modified.