Core Java - File Handling

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. We would see most commonly used example one by one:

Byte Streams :
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream andFileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file.
Eg:
    import java.io.*;
    public class FileHandling {
        public static void main(String args[]) throws IOException{
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
        in = new FileInputStream("input.txt");
        out = new FileOutputStream("output.txt");
        int c;
        while ((c = in.read()) != -1)
        out.write(c);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
        if (in != null) {
        in.close();
        }
        if (out != null){
        out.close();
        }
        }
        }
    }

Now let's have a file input.txt with the following content
Output :
    This is test for File Handling.

As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt.
So let's put above code in CopyFile.java file and do the following:
    $javac FileHandling.java
    $java FileHandling

Now we see, the flow chart of ByteStream as given below:



Character Streams :
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Characterstreams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are FileReader and FileWriter..

Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write above example which makes use of these two classes to copy an input file (having unicode characters) into an output file:

Eg:
    import java.io.*;
    public class FileHandling {
        public static void main(String args[]) throws IOException{
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
        in = new FileInputStream("input.txt");
        out = new FileOutputStream("output.txt");
        int c;
        while ((c = in.read()) != -1)
        out.write(c);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
        if (in != null) {
        in.close();
        }
        if (out != null){
        out.close();
        }
        }
        }
    }

Output :
    This is test for File Handling.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:
    $javac FileHandling.java
    $java FileHandling

Standard Streams :
All the programming languages provide support for standard I/O where user's program can take input from a keyboard and then produce output on the computer screen. If you are aware of C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR.
Similar way Java provides following three standard streams are

  • Standard Input : This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in.
  • Standard Output : This is used to output the data produced by the user's program and usually a computer screen is used to standard output stream and represented as System.out.
  • Standard Error : This is used to output the error data produced by the user's program and usually a computer screen is used to standard error stream and represented as System.err.

  • Following is a simple program which creates InputStreamReader to read standard input stream until the user types a "q":
    Eg:
        import java.io.*;
        public class StdStream {
            public static void main(String args[]) throws IOException{
            InputStreamReader cin = null;
            try {
            cin = new InputStreamReader(System.in);
            System.out.println("Enter characters, 'q' to quit.");
            char c;
            do {
            c = (char) cin.read();
            System.out.print(c);
            } while(c != 'q');
            }catch(Exception e){
                e.printStackTrace();
            }finally {
            if (cin != null) {
            cin.close();
            }
            }
            }
        }
    
    
    Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This program continues reading and outputting same character until we press 'q':
    Output :
    $javac StdStream.java
    $java StdStream
    Enter characters, 'q' to quit.
    1
    1
    3
    3
    a
    a
    q
    q

    Reading and Writing Files :
    As we discussed, A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.
    Here is a hierarchy of classes to deal with Input and Output streams.

    InputStream :

    FileHandling

    OutputStream :

    FileHandling

    FileInputStream :
    This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.
    Following constructor takes a file name as a string to create an input stream object to read the file:
        InputStream f = new FileInputStream("D:/java/hello");
    
    
    Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:
        File f = new File("D:/java/hello");
        InputStream f = new FileInputStream(f);
    
    
    Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

        S.No	                Methods	                                            Description
       ------ ---------------------------------------------  -----------------------------------------------------------------------
        1	  public void close() throws IOException{}        This method closes the file output stream. Releases any system 
                                                              resources associated with the file. Throws an IOException.
    
        2	  protected void finalize()throws IOException{}   This method cleans up the connection to the file. Ensures that 
                                                              the close method of this file output stream is called when there 
                                                              are no more references to this stream. Throws an IOException.
    
        3	  public int read(int r)throws IOException{}	  This method reads the specified byte of data from the InputStream. 
                                                              Returns an int. Returns the next byte of data and -1 will be 
                                                              returned if it's end of file.
    
        4	  public int read(byte[] r) throws IOException{}  This method reads r.length bytes from the input stream into an array. 
                                                              Returns the total number of bytes read. If end of file -1 will be returned.
    
        5	  public int available() throws IOException{}	  Gives the number of bytes that can be read from this file input stream. 
                                                              Returns an int.
    
    
    There are other important input streams available, for more detail you can refer to the following links:
  • ByteArrayInputStream
  • DataInputStream


  • ByteArrayInputStream :
    The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The input source is a byte array. There are following forms of constructors to create ByteArrayInputStream objects.
    Takes a byte array as the parameter:
        ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
    
    
    Another form takes an array of bytes, and two ints, where off is the first byte to be read and len is the number of bytes to be read.
        ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, int off, int len);
    
    
    Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream.

        S.No	            Methods	                                        Description
       ------ ---------------------------------------------  -----------------------------------------------------------------------
        1	   public int read()	                          This method reads the next byte of data from the InputStream. 
                                                              Returns an int as the next byte of data. If it is end of file then it 
                                                              returns -1.
    
        2	   public int read(byte[] r, int off, int len)	  This method reads upto len number of bytes starting from off from the 
                                                              input stream into an array. Returns the total number of bytes read. 
                                                              If end of file -1 will be returned.
    
        3	   public int available()                         Gives the number of bytes that can be read from this file input stream. 
                                                              Returns an int that gives the number of bytes to be read.
    
        4	   public void mark(int read)	                  This sets the current marked position in the stream. The parameter gives 
                                                              the maximum limit of bytes that can be read before the marked position 
                                                              becomes invalid.
    
        5	   public long skip(long n)                       Skips n number of bytes from the stream. This returns the actual number 
                                                              of bytes skipped.
    
    
    Eg:
    For ByteArrayInputStream and ByteArrayOutputStream
        import java.io.*;
        public class ByteStreamTest {
            public static void main(String args[])throws IOException {
            ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
            System.out.println("Enter the data :");
            while( bOutput.size()!= 15 ) {
            // Gets the inputs from the user
            bOutput.write(System.in.read());
            }
            byte b [] = bOutput.toByteArray();
            System.out.println("----------------------------------");
            System.out.println("Print the content :");
            for(int x= 0 ; x < b.length; x++) {
            // printing the characters
            System.out.print((char)b[x] + " ");
            }
            System.out.println(" ");
            int c;
            System.out.println("----------------------------------");
            ByteArrayInputStream bInput = new ByteArrayInputStream(b);
            System.out.println("Converting characters to Upper case :" );
            for(int y = 0 ; y < 1; y++ ) {
            while(( c= bInput.read())!= -1) {
            System.out.print(Character.toUpperCase((char)c));
            }
            bInput.reset();
            }
            }
        }   
    
    
    Output :
    Enter the data :
    finish the work
    ----------------------------------
    Print the content :
    f i n i s h t h e w o r k
    ----------------------------------------
    Converting characters to Upper case :
    FINISH THE WORK


    DataInputStream :
    The DataInputStream is used in the context of DataOutputStream and can be used to read primitives. Following is the constructor to create an InputStream:
        InputStream in = DataInputStream(InputStream in);
    
    
    Once you have DataInputStream object in hand, then there is a list of helper methods, which can be used to read the stream or to do other operations on the stream.

       S.No	                    Methods	                                                                Description
      ----- ----------------------------------------------------------  -----------------------------------------------------------------
        1	public final int read(byte[] r, int off, int len)              Reads up to len bytes of data from the input stream into an 
            throws IOException                                             array of bytes. Returns the total number of bytes read into 
                                                                           the buffer otherwise -1 if it is end of file.
    
        2	public final int read(byte [] b)throws IOException             Reads some bytes from the inputstream an stores in to the 
                                                                           byte array. Returns the total number of bytes read into the 
                                                                           buffer otherwise -1 if it is end of file.
    
        3	 a) public final boolean readBooolean()throws IOException,     These methods will read the bytes from the contained  
             b) public final byte readByte()throws IOException,            InputStream. Returns the next two bytes of the InputStream
             c) public final short readShort()throws IOException,          as the specific primitive type.
             d) public final int readInt()throws IOException                 
            	                                     
        4	public String readLine() throws IOException                    Reads the next line of text from the input stream. 
                                                                           It reads successive bytes, converting each byte separately 
                                                                           into a character, until it encounters a line terminator or 
                                                                           end of file; the characters read are then returned as a String.
    
    
    Eg:
    This example reads lines given in a file input.txt and convert those lines into capital letters and finally copies them into another file output.txt.
        import java.io.*;
        public class Test{
            public static void main(String args[])throws IOException{
            DataInputStream d = new DataInputStream(new FileInputStream("input.txt"));
            DataOutputStream out = new DataOutputStream(new FileOutputStream("output.txt"));
            String count;
            while((count = d.readLine()) != null){
            String su = count.toUpperCase();
            System.out.println(su);
            out.writeBytes(su + " ,");
            }
            d.close();
            out.close();
            }
        }
    
    
    Output :
    THIS IS TEST FOR FILE HANDLING.

    FileOutputStream :
    FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.
    Here are two constructors which can be used to create a FileOutputStream object.
    Following constructor takes a file name as a string to create an input stream object to write the file:
        OutputStream f = new FileOutputStream("D:/java/hello")
    
    
    Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows:
        File f = new File("D:/java/hello");
        OutputStream f = new FileOutputStream(f);
    
    
    Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.
        S.No	            Methods	                                                    Description
       ----- ------------------------------------------------- --------------------------------------------------------------------------
        1	  public void close() throws IOException{}          This method closes the file output stream. Releases any system resources 
                                                                associated with the file. Throws an IOException.
    
        2	  protected void finalize()throws IOException{}	    This method cleans up the connection to the file. Ensures that the close 
                                                                method of this file output stream is called when there are no more references
                                                                to this stream. Throws an IOException.
    
        3	  public void write(int w)throws IOException{}	    This methods writes the specified byte to the output stream.
    
        4	  public void write(byte[] w)throws IOException{}   Writes w.length bytes from the mentioned byte array to the OutputStream.
    
    
    There are other important output streams available, for more detail you can refer to the following links:
  • ByteArrayOutputStream
  • DataOutputStream


  • ByteArrayOutputStream :
    The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer. There are following forms of constructors to create ByteArrayOutputStream objects Following constructor creates a buffer of 32 byte:
        OutputStream bOut = new ByteArrayOutputStream()
    
    
    Following constructor creates a buffer of size int a:
        OutputStream bOut = new ByteArrayOutputStream(int a)
    
    
    Once you have ByteArrayOutputStream object in hand then there is a list of helper methods which can be used to write the stream or to do other operations on the stream.
       S.No	                Methods	                                                    Description
       ----- --------------------------------------------- ------------------------------------------------------------------------------
        1	  public void reset()	                        This method resets the number of valid bytes of the byte array output stream 
                                                            to zero, so all the accumulated output in the stream will be discarded.
    
        2	  public byte[] toByteArray()	                This method creates a newly allocated Byte array. Its size would be the 
                                                            current size of the output stream and the contents of the buffer will be 
                                                            copied into it. Returns the current contents of the output stream as a byte array.
    
        3	  public String toString()                      Converts the buffer content into a string. Translation will be done according 
                                                            to the default character encoding. Returns the String translated from the 
                                                            buffer's content.
    
        4	  public void write(int w)                      Writes the specified array to the output stream.
    
        5	  public void write(byte []b, int of, int len)	Writes len number of bytes starting from offset off to the stream.
    
    
    Eg:
        import java.io.*;
        public class ByteStreamTest {
            public static void main(String[] args) throws IOException { 
            ByteArrayOutputStream boutput = new ByteArrayOutputStream(); 
            byte[] buffer = {'J', 'A', 'V', 'A'}; 
                // Use of write(byte[] buffer, int offset, int maxlen) 
            boutput.write(buffer, 0, 4); 
            System.out.print("ASCII Values of J A V A is : "); 
            // Use of toByteArray() : 
            for (byte b: boutput.toByteArray()) { 
                System.out.print(" " + b); 
            } 
    	    } 
    	} 
    
    
    Output :
    ASCII Values of J A V A is : 74 65 86 65


    DataOutputStream :
    The DataOutputStream stream let you write the primitives to an output source.
    Following is the constructor to create a DataOutputStream.
        DataOutputStream out = DataOutputStream(OutputStream out);
    
    
    Once you have DataOutputStream object in hand, then there is a list of helper methods, which can be used to write the stream or to do other operations on the stream.

       S.No	                Methods	                                                            Description
       ---- ----------------------------------------------------------  ----------------------------------------------------------
        1	public final void write(byte[] w,int off,int len)             Writes len bytes from the specified byte array starting 
            throws IOException                                            at point off , to the underlying stream.
    
        2	public final int write(byte [] b)throws IOException           Writes the current number of bytes written to this data 
                                                                          output stream. Returns the total number of bytes write 
                                                                          into the buffer.
    
        3	(a) public final void writeBooolean()throws IOException
            (b) public final void writeByte()throws IOException           These methods will write the specific primitive type data
            (c) public final void writeShort()throws IOException          into the output stream as bytes.
            (d) public final void writeInt()throws IOException	                     
    
        4	public void flush()throws IOException	                      Flushes the data output stream.
        
        5	public final void writeBytes(String s) throws IOException     Writes out the string to the underlying output stream 
                                                                          as a sequence of bytes. Each character in the string is 
                                                                          written out, in sequence, by discarding its high eight bits.
    
    
    Eg:
    This example reads lines given in a file input.txt and converts those lines into capital letters and finally copies them into another file output.txt.
        import java.io.*;
        public class Test{
            public static void main(String args[])throws IOException{
            DataInputStream d = new DataInputStream(new FileInputStream("input.txt"));
            DataOutputStream out = new DataOutputStream(new FileOutputStream("output.txt"));
            String count;
            while((count = d.readLine()) != null){
            String su = count.toUpperCase();
            System.out.println(su);
            }
            d.close();
            out.close();
            }
        }
    
    
    Output :
    THIS IS TEST FOR FILE HANDLING.
    THIS IS TEST FOR FILE HANDLING.
    THIS IS TEST FOR FILE HANDLING.


    Serialization :
    Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

    After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

    Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

    The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:

    To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface:
    
        public final void writeObject(Object x)throws IOException
    
    
    The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:
        
        public final Object readObject()throws IOException, ClassNotFoundException
    
    
    This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.
    To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface:
        import java.util.*;
        public class Employee implements java.io.Serializable{
            public String name;
            public String address;
            public transient int SSN;
            public int number;
            public void mailCheck(){
            System.out.println("Mailing a check to "+ name+" "+ address);
            }
        }   
    
    
    Notice that for a class to be serialized successfully, two conditions must be met:
  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
  • If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.


    Serializing an Object :
    The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.
    When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.
    Note : When serializing an object to a file, the standard convention in Java is to give the file a .serextension.
        import java.util.*;
        import java.io.*;
        public class SerializeDemo{
            public static void main(String[] args){
            Employee e =new Employee();
            e.name ="Reyan Ali";
            e.address ="Phokka Kuan, Ambehta Peer";
            e.SSN =11122333;
            e.number =101;
            try{
            FileOutputStream fileOut =new FileOutputStream("employee.ser");
            ObjectOutputStream out=new ObjectOutputStream(fileOut);
            out.writeObject(e);
            out.close();
            fileOut.close();
            }catch(IOException i){
            i.printStackTrace();
            }
            }
        }
    
    
    Deserializing an Object :
    The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:
        import java.io.*;
        public class DeserializeDemo{
            public static void main(String[] args){
            Employee e =null;
            try{
            FileInputStream fileIn =new FileInputStream("employee.ser");
            ObjectInputStream in=new ObjectInputStream(fileIn);
            e =(Employee)in.readObject();
            in.close();
            fileIn.close();
            }catch(IOException i){
            i.printStackTrace();
            return;
            }catch(ClassNotFoundException c){
            System.out.println("Employee class not found");
            c.printStackTrace();
            return;
            }
            System.out.println("Deserialized Employee...");
            System.out.println("Name : "+ e.name);
            System.out.println("Address : "+ e.address);
            System.out.println("SSN : "+ e.SSN);
            System.out.println("Number : "+ e.number);
            }
        }
    
    
    Output :
    DeserializedEmployee...
    Name : ReyanAli
    Address : PhokkaKuan,AmbehtaPeer
    SSN : 0
    Number : 101

    Here are following important points to be noted:
  • The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.
  • Notice that the return value of readObject() is cast to an Employee reference.
  • The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.



  • File Navigation and I/O :
    There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.
  • File Class
  • FileReader Class
  • FileWriter Class

  • File Class :
    Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion etc. The File object represents the actual file/directory on the disk.
    There are following constructors to create a File object:

    Following syntax creates a new File instance from a parent abstract pathname and a child pathname string
        File(File parent, String child);
    
    
    Following syntax creates a new File instance by converting the given pathname string into an abstract pathname.
        File(String pathname)
    
    
    Following syntax creates a new File instance from a parent pathname string and a child pathname string.
        File(String parent, String child)
    
    
    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.

       S.No	             Methods	                                                Description
       ---- -------------------------------------     -----------------------------------------------------------------------------
        1	    public String getName()                 Returns the name of the file or directory denoted by this abstract 
                                                        pathname.
    
        2	    public String getPath()                 Converts this abstract pathname into a pathname string.
    
        3	    public boolean isAbsolute()	            Tests whether this abstract pathname is absolute. Returns true if this 
                                                        abstract pathname is absolute, false otherwise
    
        4	    public String getAbsolutePath()         Returns the absolute pathname string of this abstract pathname.
    
        5	    public boolean canRead()	            Tests whether the application can read the file denoted by this abstract 
                                                        pathname. Returns true if and only if the file specified by this abstract 
                                                        pathname exists and can be read by the application; false otherwise.
    
        6	    public boolean canWrite()	            Tests whether the application can modify to the file denoted by this 
                                                        abstract pathname. Returns true if and only if the file system actually 
                                                        contains a file denoted by this abstract pathname and the application is 
                                                        allowed to write to the file; false otherwise.
    
        7	    public boolean exists()                 Tests whether the file or directory denoted by this abstract pathname exists.
                                                        Returns true if and only if the file or directory denoted by this abstract 
                                                        pathname exists; false otherwise.
    
        8	    public boolean isDirectory()            Tests whether the file denoted by this abstract pathname is a directory. 
                                                        Returns true if and only if the file denoted by this abstract pathname 
                                                        exists and is a directory; false otherwise.
    
        9	    public boolean isFile()                 Tests whether the file denoted by this abstract pathname is a normal file. 
                                                        A file is normal if it is not a directory and, in addition, satisfies other 
                                                        system-dependent criteria. Any non-directory file created by a Java 
                                                        application is guaranteed to be a normal file. Returns true if and only if 
                                                        the file denoted by this abstract pathname exists and is a normal file; 
                                                        false otherwise.
    
        10	    public long lastModified()              Returns the time that the file denoted by this abstract pathname was last 
                                                        modified. Returns a long value representing the time the file was last 
                                                        modified, measured in milliseconds since the epoch 
                                                        (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if 
                                                        an I/O error occurs.
                                                                    
        11	    public long length()                    Returns the length of the file denoted by this abstract pathname. 
                                                        The return value is unspecified if this pathname denotes a directory.
    
        12	    public boolean mkdir()                  Creates the directory named by this abstract pathname. Returns true if 
                                                        and only if the directory was created; false otherwise.
    
        13	    public boolean createNewFile() 	        Atomically creates a new, empty file named by this abstract pathname if 
                throws IOException                      and only if a file with this name does not yet exist. Returns true if 
                                                        the named file does not exist and was successfully created; false if the 
                                                        named file already exists.
    
        14	    public boolean delete()                 Deletes the file or directory denoted by this abstract pathname. If this 
                                                        pathname denotes a directory, then the directory must be empty in order 
                                                        to be deleted. Returns true if and only if the file or directory is 
                                                        successfully deleted; false otherwise.
    
        15	    public boolean mkdir()                  Creates the directory named by this abstract pathname. Returns true if 
                                                        and only if the directory was created; false otherwise.
    
        16	    public boolean renameTo(File dest)	    Renames the file denoted by this abstract pathname. Returns true if and 
                                                        only if the renaming succeeded; false otherwise.
    
        17	    public boolean setReadOnly()            Marks the file or directory named by this abstract pathname so that only 
                                                        read operations are allowed. Returns true if and only if the operation 
                                                        succeeded; false otherwise.
    
        18	    public int compareTo(Object o)          Compares this abstract pathname to another object. Returns zero if the 
                                                        argument is equal to this abstract pathname, a value less than zero if 
                                                        this abstract pathname is lexicographically less than the argument, or 
                                                        a value greater than zero if this abstract pathname is lexicographically 
                                                        greater than the argument.
                                                                    
        19	    public boolean equals(Object obj)	    Tests this abstract pathname for equality with the given object. 
                                                        Returns true if and only if the argument is not null and is an abstract 
                                                        pathname that denotes the same file or directory as this abstract pathname.
    
        20	    public String toString()	            Returns the pathname string of this abstract pathname. 
                                                        This is just the string returned by the getPath() method.
    
    
    Eg:
        package com.sdbt.io;
    
        import java.io.*;
        public class DemoFile { 
            public static void main(String[] args) {
            File f = null;
            String[] strs = {"input.txt", "output.txt"};
            try{
            // for each string in string array
            for(String s:strs ){
            // create new file
            f= new File(s);
    
            // true if the file is executable
            boolean bool = f.canExecute();
    
            // find the absolute path
            String a = f.getAbsolutePath();
    
            // prints absolute path
            System.out.print(a);
    
            // prints
            System.out.println(" is executable: "+ bool);
            }
            }catch(Exception e){
            // if any I/O error occurs
            e.printStackTrace();
            }
            }
    	}
    
    
    Output :
    input.txt is executable: true
    output.txt is executable: true


    FileReader Class :
    This class inherits from the InputStreamReader class. FileReader is used for reading streams of characters. This class has several constructors to create required objects.
    Following syntax creates a new FileReader, given the File to read from.
        FileReader(File file)
    
    
    Following syntax creates a new FileReader, given the FileDescriptor to read from.
        FileReader(FileDescriptor fd)
    
    
    Following syntax creates a new FileReader, given the name of the file to read from.
        FileReader(String fileName)
    
    
    Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files.
       S.No	            Methods	                                                              Description
       ----  -----------------------------------------------  -----------------------------------------------------------------------------
        1	  public int read() throws IOException	           Reads a single character.Returns an int, which represents the character read.
        2	  public int read(char [] c,int offset,int len)    Reads characters into an array. Returns the number of characters read.
    
    
    Eg:
        import java.io.*;
        public class FileReader { 
            public static void main(String args[])throws IOException{
            File file = new File("FileReader.txt");
            
            // creates the file
            file.createNewFile();
            
            // creates a FileWriter Object
            FileWriter writer = new FileWriter(file);
            
            // Writes the content to the file
            writer.write(" This is \n the example  \n for File Reader...");
            writer.flush();
            writer.close();
            
            //Creates a FileReader Object
            FileReader fr = new FileReader(file);
            char [] a = new char[50];
            fr.read(a); // reads the content to the array
            for(char c : a)
            System.out.print(c); //prints the characters one by one
            fr.close();
            }
        }
    
    
    Output :
    This is
    the example
    for File Reader...


    FileWriter Class :
    This class inherits from the OutputStreamWriter class. The class is used for writing streams of characters. This class has several constructors to create required objects.
    Following syntax creates a FileWriter object given a File object
    
        FileWriter(File file)
    
    
    Following syntax creates a FileWriter object given a File object.
    
        FileWriter(File file, boolean append)
    
    
    Following syntax creates a FileWriter object associated with a file descriptor
    
        FileWriter(FileDescriptor fd)
    
    
    Following syntax creates a FileWriter object given a file name.
    
        FileWriter(String fileName)
    
    
    Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
        
        FileWriter(String fileName, boolean append)
    
    
    Once you have FileWriter object in hand, then there is a list of helper methods, which can be used manipulate the files.

        S.No	            Methods	                                                            Description
       ---- ------------------------------------------------    --------------------------------------------------------------------------
        1	 public void write(int c) throws IOException	     Writes a single character.
    
        2	 public void write(char [] c, int offset, int len)   Writes a portion of an array of characters starting from offset and with 
                                                                 a length of len.
    
        3	 public void write(String s, int offset, int len)    Write a portion of a String starting from offset and with a length of len
    
    
    Eg:
        import java.io.*;
        public class FileWriter { 
            public static void main(String args[])throws IOException{
            File file = new File("FileReader.txt");
            
            // creates the file
            file.createNewFile();
            
            // creates a FileWriter Object
            FileWriter writer = new FileWriter(file);
            
            // Writes the content to the file
            writer.write(" This is \n the example  \n for File Reader...");
            writer.flush();
            writer.close();
            
            //Creates a FileReader Object
            FileReader fr = new FileReader(file);
            char [] a = new char[50];
            fr.read(a); // reads the content to the array
            for(char c : a)
            System.out.print(c); //prints the characters one by one
            fr.close();
            }
        }
    
    
    Output :
    This is
    the example
    for File Reader...


    Directories in Java :
    A directory is a File which can contains a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail check a list of all the methods which you can call on File object and what are related to directories.

    Creating Directories:
    There are two useful File utility methods, which can be used to create directories:
  • The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.
  • The mkdirs() method creates both a directory and all the parents of the directory.

  • Following example creates "/tmp/user/java/bin" directory:
        import java.io.File;
        public class CreateDir {
            public static void main(String args[]) {
            String dirname = "/tmp/user/java/bin";
            File d = new File(dirname);
            
            // Create directory now.
            d.mkdirs();
            }
        }
    
    
    Compile and execute above code to create "/tmp/user/java/bin".

    Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.


    Listing Directories:
    You can use list( ) method provided by File object to list down all the files and directories available in a directory as follows: Eg:
        import java.io.*;
        public class Dir {    
            public static void main(String[] args) {
            File file = null;
            String[] paths;
            try{
            // create new file object
            file = new File("/tmp");
    
            // array of files and directory
            paths = file.list();
    
            // for each name in the path array
            for(String path:paths){
                // prints filename and directory name
                System.out.println(path);
                }
                }catch(Exception e){
                // if any error occurs
                e.printStackTrace();
                }
            }
        }
    
    
    Output :
    test1.txt
    test2.txt
    ReadDir.java
    ReadDir.class

    (Core Java - Multithreading)