Monday, 30 January 2017

File Handling

File Handling in Java
So far we have seen that we can store data in variables and arrays. But the data stored in variables and arrays will lost when program is terminated. Theses storages are temporary and it is difficult to store large volume of data in variables and arrays. To store data permanently in hard disk we use file system. Files are the collection of related records and records are collection of fields and fields are group of characters. Characters are Unicode characters and size of characters is two byte.

Managing data in file is called file processing which includes creating, updating, and manipulating data in the files. Java provides various features to read and write data into the files. Java supports reading and writing of class objects directly in the file. Process of reading and writing objects in a file is known as object serialization. 

Streams
Input in file processing means flow of data from a device (such as keyboard, memory, hard disk) to the program. Input can also be from network devices and other programs to a program. Similarly output means flow of data from a program to a device (computer screen, printer, memory, hard disk) or network or any other program. Stream in java represents ordered sequence of data. A stream represents object oriented interface between program and input output devices.

In java streams are of two types: one is input stream and other is output stream. The input stream reads data from a file (device) and sends it to the program. The output stream sends data from a program to file (device).

Java Stream Classes
Java.io package contains various stream classes that supports input output processing of all type of data.
Stream classes can be grouped into two categories:
1.      Byte Stream Classes: Supports input output operations on bytes.
2.      Character Stream Classes: Supports input output operations on characters.

            Byte Stream Class:  There are two types of byte stream classes in java: Input Stream Class and Output Stream Classes.
            Input Stream Class
            A super class InputStram is used to read data (byte or array of byte) from an input           source (file, memory etc). It is an abstract class which defines interfaces for input         streams that are inherited from it.
            The class hierarchy of subclasses inherited from InputStram is as follows:
1.      ByteArrayInputStream
2.      FileInputStream
3.      ObjectInputStream
4.      FilterInputStream
5.      PipedInputStream
6.      StringBufferInputStream
7.      FilterInputStream
a.       BufferedInputStream
b.      DataInputStream
c.       LineNumberInputStream
d.      PushbackInputStream

InputStram is an abstract class so instance of this class cannot b created. We will need to use subclasses inherited from this class.

 Output Stream Classes
A super class outputStram is used to write data (byte or array of byte) to destination output source (file, memory etc). It is also an abstract class which defines interfaces for output streams that are inherited from it.

            The class hierarchy of subclasses inherited from outputStram is as follows:
1.      ByteArrayOutputStream
2.      FileOutputStream
3.      ObjectOutputStream
4.      FilterInputStream
5.      PipedOutputStream
6.      StringBufferInputStream
7.      FilterOutputStream
a. BufferedOutputStream
b.DataOutputStream
c. PrintStream
            Character Streams Classes
            It supports 2 byte (16 bit) Unicode character input output functionality. There are two       types of character stream classes in java: Reader Class and Writer Classes.
           
            Reader:
            The class hierarchy of subclasses inherited from Reader is as follows:
1        BufferedReader
·         LineNumberReader
2        CharAraayReader
3        PipedReader
4        StringReader
5        FilterReader
·         PushbackReader
6        InputStreamReader
·         FileReader
            Writer:
            The class hierarchy of subclasses inherited from Writer is as follows:
1        BufferedWriter
2        CharAraayWriter
3        FileWriter
4        PipedWriter
5        PrintWriter
6        String Writer
7        OutputStreamWriter
·   FileWriter
           
            Reader Classes
            Reader class is available in java.io packages and used to provide standard I/O facilities     to read text from file or keyboard. It acts as abstract class to read character stream. The         subclass must implement read(char[], int, int), and close() methods. The reader class          can be categorized into sub classes. Most of the subclasses override some methods to       provide high efficiency and additional functionality.           
            InputStreamReader:
            It is bridge from byte stream to character stream; it reads bytes from the input and             decodes them into Unicode character. InputStreamReader class reads characters from a           byte input stream.   When we create InputStreamReader class we specify InputStream     from which it reads the byte.
            BufferedReader:
            It is a subclass of Reader class. It reads character input stream from memory which is        known as a buffer maintains state. We can specify the buffer size or we can use default           buffer size. BufferedReader converts un buffered stream into a buffered stream. The un         buffered stream object is passed to the constructor for a buffered stream class.             BufferedReader class provides following methods to perform reading operations.
            read(): It reads a single character and returns integer value.
            read(char[] cbuf, int off, int len): It reads characters into an array and returns integer.
            readLine(): Reads a line of text. Line is terminated by (‘\n’). Returns a string.
            close(): it closes the opened stream. Returns void.
             Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class FileHandling {
      
              public static void main(String[] args) throws IOException
             
              {
                     InputStreamReader inp = new InputStreamReader(System.in);
                     BufferedReader br = new BufferedReader(inp);
                    
                     System.out.println("Enter text : ");
                     String str = br.readLine();
                     System.out.println("You entered String : ");
                     System.out.println(str);
              }
      
}
Output of this program is:
Enter text :
This is my first stream reader program
You entered String :
This is my first stream reader program
InputStreamReader(System.in) is used to define source of data. We can have different source of data like: file, network or keyboard.       
System.in : It is a standard input, used to read data from the keyboard.
The complete statement tells InputStreamReader(System.in) that we have to read data from the keyboard. We have taken inp as an instance of the InputStreamReader.
BufferedReader(inp): is a class which is used to hold (store) the input data. Input to this class is inp which tells input source. We have created br as aan instance of BufferedReader.
br.readLine(): Reads a line (line ends with \n) from the input (keyboard in this example).
When we run this program it will display a message “Enter text :”, when we enter some text and press enter key the line is completed and it display same line on the screen.

The File Class
File class is the part of java.io package and used to create file and directories. File class contains various methods to support various operations on the file such as: creating, opening, closing, deleting a file and many more. The stream provides simple model for reading and writing data but it doesn’t support al the operations on the files. So we use File class and its methods to perform various operations on the file.

Example:
This example checks whether a file is available or not, if not available then creates it.
import java.io.File;
import java.io.IOException;


public class FileHandling {
      
       public static void main(String[] args) throws IOException
       {
              File myFile;
             
              myFile = new File ("myfile.txt");
             
              if(!myFile.exists())
              {
                     myFile.createNewFile();
                     System.out.println("A file: \"myfile.txt\" has been created to                           the current project directory");
              }
       }
}

The output of this program is:   
A file: "myfile.txt" has been created to the current project directory.
In above example we created an instance myFile of File class and passed myFile.txt as the name of the file. myFile.exists() statement checks whether file exists or not. If file doesn’t exists then control will go to into if condition. In if it creates file   myFile.createNewFile() and display messege given in next line.
Reading Writing Bytes (File Input Output Streams):
Java supports following I/O file streams
1.      FileInputStream : Reading Bytes
2.      FileOutputStream : Writing Bytes
FileInputStream: This class is subclass of InputStram class, it reads bytes from a given file. The read() method of this class reads a byte or array of bytes from the file and returns -1 if end of file reached. We use this class with a BufferedInputStream and DataInputstream to read binary data from a given file. To read text data from a file, we use InputStreamReader and BufferedReader classes. This class throws FileNotFoundException, if file is doesn’t exist on given location.
Example:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class ReadFile {
      
       public static void main(String[] args) throws IOException
       {
              File fileName;
              fileName = new File("myfile.txt");
             
              if(!fileName.exists()&& fileName.length()<0)
                     System.out.println("The specified file is not exist");
              else
              {
                     FileInputStream fiStream = new FileInputStream(fileName);
                     byte data;
                     do
                     {
                           data=(byte)fiStream.read();
                           System.out.print((char)data);
                     }
                    
                     while(data!=-1);
                     fiStream.close();
              }
       }
}
The output of this program is: it display’s complete data of file.
First we check whether file exists or not and we also check size of the file with the help of fileName.exists and fileName.length methods. If file exists and length of the file is grater then zero then we create an instance fiStream of  FileInputStream(fileName). Then we read data of file in a byte variable data with the help of fiStream.read() method and display data on the screen with the help of System.out.print((char)data) statement.  
FileOutputStream: This class is a subclass of OutputStream class which writes data in to a given file. The write () method of this class is used to writes a byte or array of bytes into the specified file. We typically use this class with a BufferedOutputStream and a DataOutputStream class to write binary data to a given file.  We use PrintWriter, BufferedWriter and an OutputStreamWriter classes to write text into a specified file.
Example:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


public class WriteFile {
      
       public static void main(String[] args) throws IOException
      
       {
              File outputFileName = new File ("outputfile.txt");
              FileOutputStream fOpen=new FileOutputStream (outputFileName);
             
              if (outputFileName.exists ())
              {
                     String myString="Data written to file using FileOutputStream";
                     fOpen.write (myString.getBytes ());
                     fOpen.flush ();
                     fOpen.close ();
                     System.out.println ("Data written to file successfully!");
              }
              else
              System.out.println ("This file is doesn't exists");
       }
}
The output of the program is: Data written to file successfully!
This program first checks whether file exists or not, if file exists it creates a string myString and write this string into the file using fOpen.write() method. In the statement  myString.getBytes ()); the method getBytes converts the string into the array of bytes.

We can take array instead of string and write that directly into the file without any conversion.
Example:
import java.io.FileOutputStream;
import java.io.IOException;


public class WriteBytesinFile {
      
       public static void main(String[] args)
      
       {
              byte myCities[] = {'J','A','I','P','U','R','\n',                                                              'J','O','D','H','P','U','R','\n',
                                  'M','U','M','B','A','I','\n',
                                  'D','E','L','H','I'};
              FileOutputStream fOpen = null;
             
              try{
                    
                     fOpen = new FileOutputStream ("citiesfile.txt");
                     fOpen.write (myCities);
                     fOpen.close ();
                     System.out.println ("Data written to file successfully!");
              }catch(IOException e)
              {
                     System.out.println (e);
                     System.exit(-1);
              }
       }     
}
Output of the file is: Data written to file successfully!
In this example basically two things are different from previous one. First is we have taken array of bytes instead of string to write data into the file. Second is we have handled exception differently. Here we are not checking existence of file. We have simply used try catch block, if any exception appears it will display error message.
We can copy data from one file to another file using streams.
Example:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class FileHandling {
      
       public static void main(String[] args)
      
       {
              FileInputStream fInput = null;
              FileOutputStream fOutput = null;
                          
              byte byteData;
              try{
                    
                     fInput = new FileInputStream("myInputFile.txt");
                     fOutput = new FileOutputStream ("myOutputFile.txt");
                    
                     //Read data from fInput file and write into fOutput file.
                     do{
                           byteData = (byte)fInput.read();
                           fOutput.write(byteData);
                     }
                     while(byteData != -1);
                     System.out.println ("Data written to file successfully!");
                    
              }
              catch(FileNotFoundException e)
              {
                     System.out.println (e.getMessage());
              }
              catch(IOException e)
              {
                     System.out.println (e.getMessage());
              }
              finally
              {     
                     try{
                          
                           fInput.close();
                           fOutput.close();
                     }
                     catch(IOException e)
                     {
                           System.out.println (e.getMessage());
                     }
              }
             
       }     
}
The output of this program is: Data written to file successfully!

Reading Writing Characters
Subclasses of Reader and Write classes support streams that are used to handle characters. Subclasses FileReader and FileWriter are used to handle characters in files. We are taking an example in which we will copy characters of a file into another file. Create a file named myCharInputFile.txt in the folder of your project.
Example:
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileHandling {
      
       public static void main(String[] args)
      
       {
              File fInput = new File("myCharInputFile.txt");
              File fOutput = new File ("myCharOutputFile.txt");
              FileReader inReader = null;
              FileWriter outWriter = null;
                                        
              try{
                     inReader = new FileReader(fInput);
                     outWriter = new FileWriter(fOutput);
                     //Read data from fInput file and write into fOutput file.
                     int chtr;
                     while((chtr = inReader.read()) != -1)
                     {
                           outWriter.write(chtr);
                     }
                     System.out.println ("Data written to file successfully!");
              }
              catch(IOException e)
              {
                     System.out.println (e.getMessage());
              }
              finally
              {     
                     try{
                           inReader.close();
                           outWriter.close();
                     }
                     catch(IOException e)
                     {
                           System.out.println (e.getMessage());
                     }
              }
       }     
}
The output of this program is: all data from input file is copied to output file successfully.
This project creates two objects of two files:
File fInput = new File("myCharInputFile.txt");
File fOutput = new File ("myCharOutputFile.txt");

Then two file stream objects created:
FileReader inReader = null;
FileWriter outWriter = null;

Stream objects are connected to files (means files opened) as shown below:
inReader = new FileReader(fInput);
outWriter = new FileWriter(fOutput);

Read a character from the input file using chtr = inReader.read()) and write it into output file using  outWriter.write(chtr) this process is repeated upto the end of input file using while loop. At the end of file read() method returns -1.

Finally both the files are closed using close() method.
 inReader.close();
outWriter.close();








No comments: