Monday, February 16, 2009

How to verify, input location is a File or Directory in Java

Java provides a Class called File, which is under the package java.io , contains all the sufficient methods(functions), which can be used to extract almost all the important properties of the Directory or a File. In the below example LocationVerification.java as well, i have used java.io.File class to know whether the input provided by the user is a File or Folder i.e. Directory.

LocationVerification.java
-------------------------
/*
  File   : LocationVerification.java
  Purpose: Verifies the input location is File or a Directory 
  Author : Anaparthi Subrahmanyam 
  Published: 2009-02-16
  Usage Notification: Author doesnt own responsibility of any loss of data, responsibility for misuse or loss of any nature if this code is used. If possible, please provide link to this webpage.
*/
import java.io.File;

public class  LocationVerification
{
  public static void main(String[] args) 
  {
    String name = args[0];
    File f = new File(name);
    try
    {
      if(!f.exists())
      {
         throw new Exception("Invalid location!!!");
      }
       if(!f.isDirectory())
      {
         System.out.println("Location provided is a not a file directory, its a File");
      }
      else
      {
        System.out.println("Location provided is a file directory.");
      }

    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}
---------------------------------

How to execute the above file:

1. Compile it successfully
2. Execute it with providing a command line argument such as:

cmd_prompt> java LocationVerification c:\test\sample

If the third part of the above command is file then result will show  as Location is file, if its directory then result will show you a message saying its directory.




No comments:

Post a Comment