Home Java Beginners Determining if a Filename path is a file or a directory



Determining if a Filename path is a file or a directory
Posted on: June 7, 2007 at 12:00 AM
In this section, you will learn how to determining filename is a file or a directory.

Determining if a Filename path is a file or a directory

     

You can solve this problem very easily. What you need to do, just create a File object and pass some file name or a directory in it.

We are using a following methods to solve this problem.

isDirectory(): It checks whether the file is a directory or not.

getAbsolutePath(): It returns the absolute path of a file or directory.

Code of the program is given below:

import java.io.*;

public class FileOrDirectory{
  public static void main(String args[]){
  File directory = new File("Enter any 
  directory name or file name"
);
  boolean isDirectory = directory.isDirectory();
  if (isDirectory) {
  // It returns true if directory is a directory.
  System.out.println("the name you have entered 
   is a directory  : "  
+  directory);  
  //It returns the absolutepath of a directory.
  System.out.println("the path is "  
    directory.getAbsolutePath
());
  else {
  // It returns false if directory is a file.
  System.out.println("the name you have
   entered is a file  : " 
+ directory);
  //It returns the absolute path of a file.
  System.out.println("the path is "  +  
    directory.getAbsolutePath
());
  }
  }
}

 

The output of this example is given below:

C:\FileOrDirectory>java FileOrDirectory
the name you have entered is a file : FileOrDirectory
the path is C:\FileOrDirectory\FileOrDirectory

Download this example:

Related Tags for Determining if a Filename path is a file or a directory:
cfileobjectdirectorymethodsmethodproblemnameusingthiscreatechecktoeilitnotcaninnopassasmcajemdirmeobjprodotorssdirectsoctoreedirectatkisirhallfolloweaandarwingssthsthatctojeprndodsomolo


More Tutorials from this section

Ask Questions?    Discuss: Determining if a Filename path is a file or a directory   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.