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
 

Saturday 7 March 2015

Difference between equals method and "==" operator & Examples in java


         First difference between them is, equals() is a method defined inside the java.lang.Object class
and == is one type of operator and you can compare both primitive and objects using equality operator in java.

         Second difference between equals and == operator is that ,== is used to check reference or memory address of the objects whether they point to same location or not , and equals() method is used to compare the contents of the object e.g in case of comparing String its characters, in case of integer its numeric values etc.

        Third difference between equals and == operator is that, you can not change the behavior of  == operator but we can override equals() method and define the criteria for the objects equality.

Summary:--

 1) Use == to compare primitive e.g boolean, int, char etc while use equals() to compare objects in
      Java.

 2)  ==  return true if two reference are of same object .  Results of equals() method depends on
    overridden implementation.

 3) For comparing String use equals()  instead of  == equality operator.


Some interview questions & answers based on equals() method and == operator :

1) Can two objects which are not equal have same hashCode?
  
     Yes, two objects which are not equal by equals() method can still returns the same hashCode.    


2) What happens if you compare an object with null using equals() method?

          When null object is passed as an argument to equals() method, it should return false, it must not throw NullPointerException , but if you call equals method on reference, which is  null it will throw NullPointerException. That's why it's better to use == operator for comparing null.


3) What is the output of given code?    


public class StringEx {

       public static void main(String[] args){
            
            String s1 = "Hello";
            String s2 = new String("Hello");
            String s3 = new String("Hello"); 
                                   
            if(s1.equals(s2)) {
                 System.out.println("s1 equals to s2");
            } else {
                 System.out.println("s1 not equals to s2");
            }
                                   
            if(s2.equals(s3)) {
                 System.out.println("s2 equals to s3");
            } else {
                 System.out.println("s2 not equals to s3");
            } 
      }
}

Output:-  s1 equals s2
                 s2 equals s3

   
 4)  What is the output of given code?


public class StringEx {

       public static void main(String[] args){
            
            String s1 = "Hello";
            String s2 = new String("Hello");
            String s3 = new String("Hello"); 
                                   
            if(s1 == s2) {
                 System.out.println("s1 equals to s2");
            } else {
                 System.out.println("s1 not equals to s2");
            }
                                   
            if(s2 == s3) {
                 System.out.println("s2 equals to s3");
            } else {
                 System.out.println("s2 not equals to s3");
            } 
      }
}

Output:-  s1 not equals to s2
                 s2 not equals to s3


Related Post:--
1) String Related Interview Questions & Answers
2) Why String is immutable or final in java?