Showing posts with label IO streams. Show all posts
Showing posts with label IO streams. Show all posts

Thursday 25 April 2013

File handling in java


File handling concept in Java
Java provide java.io package to deal with the file handling stuffs like creating a file, reading from it and writing into the file. We can simple do it by importing java.io package in our class and creating the object of the File class by giving the path (physical path on the hard drive) of the file as an argument. We can also create the file if it doesn’t exists on the path given in the argument as shown in the below example

import java.io.*;

public class demoFile {

                /**

                 * @param args

                 */

                public static void main(String[] args) {

                                // TODO Auto-generated method stub

                                File fl = new File("d://demo.txt");

                                if(fl.exists())//Checks if the file exists or not

                     {
                          System.out.println("The file is already exists");
                          System.out.println(fl.canRead()); //Check the read permission of the file or directory
                          System.out.println(fl.canWrite());//Check the write permission of the file or directory
                          System.out.println(fl.isFile());//Check the mentioned file is file or not
                          System.out.println(fl.listFiles());//List all the files in folder(Gives Array)
                          System.out.println(fl.getPath());//Get the ralative path of the file
                          System.out.println(fl.getAbsolutePath());//Get the absolute path of the file
                           System.out.println(fl.delete());//This wil delete the file or directory.
                                    
                     }

                                else

                                {

                                                try

                                                {

                                                                fl.createNewFile();

                                                                System.out.println("New file is created");

                                                }

                                                catch(Exception e)

                                                {

                                                                System.out.println("The exception is :- "+e);

                                                }

                                }

                }

}

Same program can be written to handle directories

import java.io.*;

public class demoFile1 {

                /**

                 * @param args

                 */

                public static void main(String[] args) {

                                // TODO Auto-generated method stub

                                File fl = new File("d://demo");

                if(fl.exists())//Checks if the file exists or not

                     {
                          System.out.println("The Directory is already exists");
                          System.out.println(fl.canRead()); //Check the read permission of the file or directory
                          System.out.println(fl.canWrite());//Check the write permission of the file or directory
                          System.out.println(fl.isDirectory());//Check the mentioned file is file or not
                          System.out.println(fl.listFiles());//List all the files in folder
                          System.out.println(fl.getPath());//Get the ralative path of the file
                          System.out.println(fl.getAbsolutePath());//Get the absolute path of the file
                         System.out.println(fl.delete());//This wil delete the file or directory.

                     }

                                else

                                {

                                                try

                                                {

                                                                fl.mkdir(); //Create the new directory

                                                                System.out.println("New Directory is created");

                                                }

                                                catch(Exception e)

                                                {

                                                                System.out.println("The exception is :- "+e);

                                                }

                                }

                }

}

If  demo.txt does not exists on the d drive, The first time you run this program it will give message as “New file is created” but when you run it again it will give message as “The file already exists” means it created the file on first go.
Now file creation is done, what’s next. As in real scenario the files are used to store the data so that we can read them in future. Java is not any exception in this case. Java provides FileWriter and FileReader classes for this purpose.

Example:-
import java.io.*;

public class fileWriterDemo {
                /**
                 * @param args
                 */
                public static void main(String[] args) {
                                // TODO Auto-generated method stub
                                File fl = new File("d://demo1.txt");
                                try
                                {
                                                char[] ch = new char[500];
                                                FileWriter fw = new FileWriter(fl);
                                                fw.write("Here is the first line of the file");
                                                fw.append("\nHere is the second line of the file");
                                                fw.flush();
                                                fw.close();
                                                FileReader fr = new FileReader(fl);
                                                System.out.println("Size of the file is :- "+fr.read(ch));
                                                fr.close();
                                                for(char c : ch)
                                                {
                                                                System.out.println(c);
                                                }
                                               
                                }
                                catch(Exception e)
                                {
                                                System.out.print("The exception is :- "+e);
                                }
                               

                }

}

Now you must be wondering about the three methods append (), flush () and close () we used in the program. Let me clear you that what’s the purpose of these methods.
Append () :-  This method will write the data in the file as write method but at the end of the preexisting data. It saves the already written data and writes the new data at the end of the file. It can be written in FileWriter also as:
FileWriter fw = new FileWriter(fl, true);
 It will not over write the file content rather it always append the content in file.


Flush():- It gives us the surety that everything in buffer is processed and no data will be lost so before calling  the close method flush() method should be called.
Close ():- File IO operation may take resources of operating systems so we need to call the close method to free up the resources.
Although the above example used FileWriter and FileReader classes for writing and reading the data from the file but these classes are not commonly used these days because of their limitations .

Limitations of the FileWriter and FileReader classes

·         They can only handle the small data as data need to be written and read character by character.
·         As you may noticed in above example that for writing the data into the next line we need to write ‘\n’ this.
·         The array should be used for reading the data from the file so its size should be declared in advance which can result into the loss of memory (if we declare the size bigger than the files data) or data can be lost (if we declare the size less than the files data).
So here comes the concept of BufferedReader and BufferedWriter to overcome the limitations of the FileReader and FileWriter.




What is Serialization in java
Serialization is used to write a object to a file or the port of some other machine. We can transfer the object by serializing it. This can be done as in the below example:
We need to implement the Serializable interface to the class whose object needs to be Serialized as
import  java.io.*;
public class className implements Serializable


and to write the object you should create the ObjectOutputStream as

FileOutputStream fileOut =
         new FileOutputStream("fileName");
         ObjectOutputStream out =
                            new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
          fileOut.close();
This process is called Serialization.
 
This code should be written in try-catch block and similarly we read the the serialized object again by ObjectInputStream