Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.9. Code exercise 9

5.8.9. Code exercise 9
Last updated: 27 January 2013.

Write a method named getMoreRecentlyModifiedFile(String directory) that returns the name of the more recently modified file in the given directory (excluding subdirectories). If the string argument is null, the method returns null. Otherwise, if the string argument denotes a file that is not a directory or does not exist or cannot be read or is empty, the method prints an error message to the standard output and returns null.


import java.io.File;

public final class Practice {

   
public String getMoreRecentlyModifiedFile(String directory){
         
if(directory == null)
               
return null;

          File result =
null;
          File dir =
new File(directory);

         
if(! dir.exists()){
               
System.out.println(directory + " does not exist");
               
return null;
         
}

         
if(! dir.isDirectory()){
               
System.out.println(directory + " is not a directory");
               
return null;
         
}

         
if(! dir.canRead()){
               
System.out.println(directory + " cannot be read");
               
return null;
         
}

         
if(dir.listFiles().length == 0){
               
System.out.println(directory + " is empty");
               
return null;
         
}

         
for(File f : dir.listFiles()){
               
if(f.isFile()){
                     
if(result == null)
                           
result = f;

                     
if(f.lastModified() > result.lastModified())
                           
result = f;
               
}
          }

         
if(result == null)
               
return null;

         
return result.getName();
   
}

}


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.9. Code exercise 9
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.10. Code exercise 10

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7