8. Sockets, Files, and Streams
Activity 1: Writing the Directory Structure to a File
Solution
- Import the relevant classes to get this example to work. Basically you will be working with collections, files, and the associated exceptions.
import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections;
- Determine the folder you will start looking for directories from. Let's assume you start from
user.home
. Declare a Path object linking to that folder.Path path = Paths.get(System.getProperty("user.home"));
- Next you will call
File.walkFileTree
, which will allow you iterate through a folder structure up to a certain depth. In this case, you can set whatever depth you want, for example10
. This means the program will dig up to10
levels of directories looking for files.Files.walkFileTree(path, Collections.emptySet(), 10, new SimpleFileVisitor<Path>() { [...]
- The approach in this...