Likes

Java Lab_14_Ans_3

3. Write a Java main that creates a PathMatcher class and uses FileVisitor to recursively delete a file or directory pattern.

SOLUTION


1. Open the project RecursiveOeleteExercise m the practices director.-.
2. Expand the Source Packages folders.
3. Open the Delete .java class file. This is the class that contains the nain method. The mam class accepts two arguments: the first is the starting path and the other the pattern to delete.
4. You must code the remainder of this class. Look at the comments for hurts as to what to do.
a. Start by creating a PathMatcher object from tire search string passed in as tire second argument. To obtain a PatW’atcher instance, you will need to use tire FileSystems class to get a path matcher instance from tire default file system.
b. Create a Path object from tire first argument.
c. If tire starting path is a file, check it against tire pattern using tire PatW’atcher instance that you created. If there is a match, delete tire file, and then terminate tire application.
d. If tire starting path is a directory, create an instance of tire CeleteFile-ree With the Startmg directory and tire Pathllatcher object as initial arguments in tire constructor. Pass tire startmg directory and the file tree to a Files..isl<=ile7ree method to recursively look for the pattern to delete.
e. Fix air.- missing unports.
f. Save the Delete class.
5. Open the Delete'ileTree class file. This class unplements 'ileVisitor. This class recursively looks for instances of files or directories that match the Psth'iatcher object passed into the constructor. This class is complete with the exception of the delete method.
a. The delete method is called by the preVisitDirectory and
vis it File methods. You must check whether the file or directory reached by these methods matches the pattern.
b. We only want to match the path name at the node, so use the Path. getFile'Jane method to obtain the file name at the end of the full path.
c. If the name matches, use the Files, delete method to attempt to delete the file pattern and print a result statement, or print an error if an lOExcepticn is thrown.
d. Save the CeleteFileTree class.
6. Run the Delete application using a temporary directory.
a. For example, if you completed the first practice, you can delete all the Java class files from the D:\Tenp directory.
b. Right-click the project and select Properties.
c. Click Run and enter the following in the Arguments text field: D:\Tenp\exanples ♦.class
d. Run the project.

No comments: