Thursday, 12 March 2015

How to create File and Directory in Java & File Related Interview Questions

           A file or a directory in the file system is represented by two abstract concept in java. These abstract concepts are java.io.File and java.nio.file.Path. The File class represents a file in the file system whereas the interface Path represents the path string of the file.
           In this tutorial we look at various operations on File or Path.

Instantiating a java.io.File:

     Before you can do anything with the file system or File class, you must obtain a File instance.

  There are following constructors to create a File object:

1)Following syntax creates a new File instance from a parent abstract pathname and a child pathname string.

        File(File parent, String child)

2)Following syntax creates a new File instance by converting the given  pathname string into an abstract pathname.

       File(String pathname)

3)Following syntax creates a new File instance from a parent pathname string and a child pathname string. 

       File(String parent, String child) 

4)Following syntax creates a new File instance by converting the given file: URI into an abstract pathname.

        File(URI uri)

     Once you have File object in hand then there is a list of helper methods which can be used manipulate the files.

Important Methods of File class:
1) boolean exists();
2) boolean createNewFile();
3) boolean mkdir();
4) boolean mkdirs();
5) boolan isFile();
6) boolean isDirectory();
7) String[] list();
8) long length();
9) boolean delete();
10) public boolean exists();

Check if File Exists:--
        Once you have instantiated a File object you can check if the corresponding file actually exists already. The File class constructor will not fail if the file does not already exists. You might want to create it now.

To check if the file exists, call the exists() method. Here is a simple example:
     package com.adnblog;
     import java.io.File;
     public class fileExistance {
            public static void main(String[] args) {
                    File file = new File("D:/ImpFiles/file.txt");
                    if(file.exists()) {
                            System.out.println("File existed");
                     }
                     else {
                            System.out.println("File doesn't exists");
                     }
            }
      }
It will print "File Existed" if file is existed in the given directory or it will print else part but it won't throw any error if file doesn't exists. 


Create a New Directory:- 

       You can use the File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose.

       The mkdir() method creates a single directory if it does not already exist & mkdirs() method creates multiple directories if it doesn't exist.

 Here is an example:

        package com.adnblog;
        import java.io.File;
        public class CreateDirectoryEx {
                public static void main(String[] args) {   
                        File file = new File("C:\\Directory1");
                        if (!file.exists()) {
                                  if (file.mkdir()) {
                                           System.out.println("Directory is created!");
                                  } else {
                                           System.out.println("Failed to create directory!");
                                   }
                         }

                              //multiple directory example
                         File files = new File("C:\\Directory2\\Sub1\\Sub");
                         if (files.exists()) {
                                   if (files.mkdirs()) {
                                          System.out.println("Multiple directories are created!");
                                   } else {
                                    System.out.println("Failed to create multiple directories!");
                                   }
                          }

                 }
         } 
 
Create New File:

          You can use the File class to create new Files if they don't already exists. The File class contains the method createNewFile() to create the new file. First to check the file is existed or not, if not then create new file.

        package com.adnblog;
        import java.io.File;
        public class fileExistance {
               public static void main(String[] args) {
                       File file = new File("D:/ImpFiles/file.txt");
                       if(!file.exists()) {
                               if(file.createNewFile()) {
                                        System.out.println("New File created!");
                               }
                               else {
                                        System.out.println("Failed to create New File");
                               }
                       }
               }
        }


File Length:-

      To read the length of a file in bytes, call the length() method. Here is a simple example:

               File file = new File("
D:/ImpFiles/file.txt");
               long length = file.length();


Rename or Move File :--

          To rename (or move) a file, call the method renameTo() on the File class. Here is a simple example:

                File file = new File("
D:/ImpFiles/file.txt");
                boolean success = file.renameTo(new File("
D:/ImpFiles/Newfile.txt"));

          As briefly mentioned earlier, the renameTo() method can also be used to move a file to a different directory. The new file name passed to the renameTo() method does not have to be in the same directory as the file was already residing in.

         The renameTo() method returns boolean (true or false), indicating whether the renaming was successful. Renaming of moving a file may fail for various reasons, like the file being open, wrong file permissions etc.


Delete File:--

 To delete a file call the delete() method. Here is a simple example:

                 File file = new File("
D:/ImpFiles/file.txt");
                 boolean success = file.delete();

        The delete() method returns boolean (true or false), indicating whether the deletion was successful. Deleting a file may fail for various reasons, like the file being open, wrong file permissions etc. 


Check if Path is File or Directory:--

       A File object can point to both a file or a directory.
    

       You can check if a File object points to a file or directory, by calling its isDirectory() method. This method returns true if the File points to a directory, and false if the File points to a file. Here is a simple example:
                package com.adnblog;
                import java.io.File;
                public class fileExistance {
                      public static void main(String[] args) {
                             File file = new File("D:/ImpFiles/file.txt");
                             if(file.
isDirectory()) {
                                    System.out.println("This is Directory!");
                             }
                             else {
                                    System.out.println("This is a File!");
                             }
                      }
                }


Read List of Files in Directory:--

      You can obtain a list of all the files in a directory by calling either the list() method or the listFiles() method.
      The list() method returns an array of String's with the file and / or directory names of directory the File object points to. 

     The listFiles() returns an array of File objects representing the files and / or directories in the 
directory the File points to.

Here is a simple example:
              package com.adnblog;

              import java.io.File;
              public class Practice {
                     public static void main(String[] args) {
                            File file = new File("/home/insta/anil/Desktop");
                            File[] filesList = file.listFiles();
                            for(File f : filesList){
                                    System.out.println(f);
                            }
                    }
              }

In the above program it will print the each file in whole path see output
         /home/insta/anil/Desktop/Resume.doc
        /home/insta/anil/Desktop/SalarySlip.pdf
        /home/insta/anil/Desktop/ImpNotes.csv

or
             package com.adnblog;
             import java.io.File;

             public class Practice {
                   public static void main(String[] args) {
                          File file = new File("/home/insta/anil/Desktop");
                          String[] filesList = file.list()
                          for(String f : filesList){
                                   System.out.println(f);
                          }
                   }

             }

In the above program it will print the each file name itself not an path.
       Resume.doc
       SalarySlip.pdf
       ImpNotes.csv
 

No comments:

Post a Comment