Java OCA OCP Practice Question 2476

Question

Which definition of class MyFileVisitor will enable the following code to delete recursively all files that are smaller than 100 bytes in size?

Path path = Paths.get("/myHomeDir");
Files.walkFileTree(path, new MyFileVisitor());
a  class MyFileVisitor implements FileVisitor<Path> {
       public FileVisitResult visitFile(Path file, 
         BasicFileAttributesattrs) throws IOException{
           if (attrs.size() <= 100) {
               Files.delete(file);
           }/*from  w w  w. j  a va  2s.  c o  m*/
           return FileVisitResult.CONTINUE;
       }
   }

b  class MyFileVisitor extends SimpleFileVisitor<Path> {
       public FileVisitResult visitFile(Path file, 
         BasicFileAttributesattrs) throws IOException{
           if (attrs.size() <= 100) {
               Files.delete(file);
           }
           return FileVisitResult.CONTINUE;
       }
   }

c  class MyFileVisitor implements FileVisitor<Path> {
       public FileVisitResult visitFile(Path file,
         BasicFileAttributes attrs) throws IOException{
           if (attrs.size() <= 100) {
               Files.delete(file);
           }
           return FileVisitResult.CONTINUE;
       }
       public FileVisitResult preVisitDirectory(Path dir,
                             BasicFileAttributes attrs) {}
       public FileVisitResult postVisitDirectory(Path dir,
                                    IOException exc) {}
       public FileVisitResult visitFileFailed(Path file,
                                IOException exc) {}
    }

 d  class MyFileVisitor extends SimpleFileVisitor {
        public FileVisitResult visitFile(Path file, 
           BasicFileAttributesattrs) throws IOException{
            if (attrs.getSize() <= 100) {
                Files.deleteFile(file);
            }
            return FileVisitResult.CONTINUE;
        }
    }

 e  Compilation error
 f  Runtime exception


b

Note

Option (a) is incorrect because it won't compile.

The FileVisitor interface defines four methods: preVisitDirectory(), postVisitDirectory(), visitFile(), and visitFileFailed().

Class MyFileVisitor in this option implements only one method.

Option (c) is incorrect.

Though class MyFileVisitor implements all the methods of the FileVisitor interface, methods preVisitDirectory(), postVisitDirectory(), and visitFileFailed() don't return a value.

All these methods must return a value of type FileVisitResult.

Option (d) is incorrect because the correct method name to get the file size from BasicFileAttributes is size.

The correct method name to delete a file using class Files is delete.




PreviousNext

Related