X

Play AlgoQuiz

Rate Us :



Share with Friends :

Menu

File Handling :

We can write two types of applications in the reference of file programming :-

  • Non-persistent application / Volatile application




  • Persistent application / Non-volatile application




Non-persistent application / Volatile application :-

The result of non-persistent application is stored in main memory (primary memory) temporarily. As long as power is on, the data will be available and once the power is off, the data will be lost. All the previous examples provided in the context is an example of non-persistent application.


Persistent application / Non-volatile application :-

The result of persistent application is stored permanently. The process of storing the data permanently is called data persistency. It can be achieved by using file concept or by using database software.

It is recommended to store the data permanently in the form of database software so that the data cannot be manipulated by any unauthorized user because most of the popular database products provides effective security in the form of username and password.


Input :-

The data or information which is given to a program or which flow inside the program is called input.


Output :-

The data or information which is given by the program or which flow outside the program is called output.


Record :-

Collection of field values (data members) are called records.


Stream :-

Stream is a class which provide a set of methods for input and output operations. It is a continues flow of data/bytes/bits between main memory (i.e. primary memory) and secondary memory.


I/O Stream :-

An I/O Stream represents an input source and an output destination. It can represent different kind of sources and destinations including disk files, devices, other programs etc. Streams support many different kind of data including simple bytes, primitive data types, localized characters and objects. A program uses an input stream to read data from a source and uses an output stream to write data to a destination. All I/O Stream classes are available in java.io package.


Types of streams :-


Based on transferring the data in the form of bytes between main memory (primary memory) and secondary memory, streams are classified into two types :

  • Byte streams




  • Character streams




Byte streams :-

In byte streams the data will be transferred in the form of byte by byte i.e. byte by byte transferring the data between main memory (i.e. primary memory) and secondary memory.

Byte streams contain two types of operation :-

  • Some category of classes participates in write operation which will transfer one byte of data from main memory (i.e. primary memory) to secondary memory.

  • Some other category of classes participates in read operation which will transfer one byte of data from secondary memory to main memory (i.e. primary memory).

Write operation has predefined abstract classes and they are providing background role for concrete subclasses and hence we can't used it directly as a part of file programming. They are :-

  • OutputStream




  • FilteredOutputStream




Write operation also has bottommost concrete subclasses of abstract classes of byte stream which can be used as a part of file programming. They are :-

  • FileOutputStream




  • DataOutputStream




Read operation has predefined abstract classes and they are providing background role for concrete subclasses and hence we can't used it directly as a part of file programming. They are :-

  • InputStream




  • FilteredInputStream




Read operation also has bottommost concrete subclasses of abstract classes of byte stream which can be used as a part of file programming. They are :-

  • FileInputStream




  • DataInputStream




Methods of I/O Streams :


int read() :-

This method is used to read a byte of data from the input stream.


int read(byte[ ] b) :-

This method is used to read upto b.length bytes of data from the input stream into an array of byte.


void write(int b) :-

This method is used to write the specified byte to the file output stream.


void write(byte[ ] b) :-

This method is used to write b.length bytes from specified byte array to the file output stream.


void close() :-

This is a method used to close the file input and output streams and releases any system resources associated with the stream.


FileOutputStream :

A FileOutputStream class is an output stream class for writing data to a file. It is meant for writing streams of raw bytes. The purpose of FileOutputStream class is to open file in write mode i.e. creating an object for FileOutputStream class.


Constructors of FileOutputStream class :-


FileOutputStream(String name) :

This constructor creates an output file stream to write to the file with specified name.


FileOutputStream(File file) :

This constructor creates a file output stream to write to the file represented by the specified file object.


FileOutputStream(String name , boolean append) :

This constructor creates an file output stream to write to the file with the specified name and value of append can be either true or false depending upto following condition :

  • If the file is not existing then a new file will be created and it is opened in write mode and an object of FileOutputStream class is pointing to starting entry of file.

  • If the file with specified name is already exists and the boolean value is true (i.e. value of append is true) then existing file is opened in write mode and an object of FileOutputStream class is pointing at the end of existing data and the new data will be appended at the end of the file.

  • If the file with specified name is already exists and the boolean value is false (i.e. value of append is false) then existing file is opened in write mode and an object of FileOutputStream class is pointing to existing data and it will be overlap with new data.

Example1 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileOutputStream f = new FileOutputStream("file1"); f.write(65); f.write(66); f.write(67); f.write(68); f.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be generated by the name of file1 or if exists then overwritten in the same directory in which the Example.java file is stored and the output will be stored in that file.*\

Output :

ABCD will be stored in file1

Example2 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { byte b[ ] = {65 , 66 , 67 , 68}; FileOutputStream f = new FileOutputStream("file2"); f.write(b); f.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be generated by the name of file2 or if exists then overwritten in the same directory in which the Example.java file is stored and the output will be stored in that file.*\

Output :

ABCD will be stored in file2

Example3 :

import java.io.*; import java.util.Scanner; class Example { public static void main(String[ ] args) { FileOutputStream f = null; try { Scanner s = new Scanner(System.in); System.out.print("Enter filename to write on it : "); String filename = s.nextLine(); f = new FileOutputStream(filename , true); f.write(65); f.write(66); f.write(67); f.write(68); System.out.println("The content is written to "+filename+" file."); } catch(IOException e) { System.out.println("Unable to open file in write mode."); } catch(Exception e) { System.out.println(e); } finally { try { if(f != null) { f.close(); System.out.println("File closed."); } } catch(IOException e) { System.out.println(e); } } } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be generated by the filename specified by user using keyboard or if file exists with the specified filename using keyboard then overwritten in the same directory in which the Example.java file is stored and the output will be stored in that file.*\

Output :

Enter filename to write on it : Algo The content is written to Algo file. File closed. ABCD will be stored in Algo file

FileInputStream :

A FileInputStream class obtains input bytes from file in a file system which is depend upon the host environment. It is meant for reading streams of raw bytes. The purpose of FileInputStream class is to open the file in read mode i.e. creating an object of FileInputStream class.


Constructors for FileInputStream :-


FileInputStream(String name) :

This constructor creates an input file stream by opening a connection to an actual file by the pathname in the file system.


FileInputStream(File file) :

This constructor creates a file input stream by opening a connection to an actual file by the object file in the file system.


Note :

  • If the file exists with specified file name then file is opened successfully in read mode and an object of FileInputStream class is pointing to the starting entry of file.

  • If file is opened successfully then object of FileInputStream class contain not null and it can be used for reading the data from the file until end of file is taking place. In Java programming, end of file is indicated by -1.

  • When reading is in progress, automatically object of FileInputStream class is advancing to the next entries in the file until end of file taking place.

  • If the file with specified file name doesn't exists then file is unable to open and an object of FileInputStream contains null.

Example1 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileInputStream f = new FileInputStream("file1"); int a; while((a = f.read()) != -1) { System.out.print(a + " "); } f.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be opened by the name of file1 if exists in the same directory in which the Example.java file is stored.*\

Output :

65 66 67 68

Example2 :

import java.io.*; import java.util.Scanner; class Example { public static void main(String[ ] args) { FileInputStream f = null; try { Scanner s = new Scanner(System.in); System.out.print("Enter filename to read from it : "); String filename = s.nextLine(); f = new FileInputStream(filename); int a; while((a = f.read()) != -1) { System.out.print(a + " "); } System.out.println(); } catch(FileNotFoundException e) { System.out.println("File doesnot exist."); } catch(IOException e) { System.out.println("Unable to read from specified file."); } catch(Exception e) { System.out.println(e); } finally { try { if(f != null) { f.close(); System.out.println("File closed."); } } catch(IOException e) { System.out.println(e); } } } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be open with the filename specified by user using keyboard if exists in the same directory in which the Example.java file is stored.*\

Output :

Enter filename to read from it : Algo 65 66 67 68 File closed.

Example3 :

import java.io.*; import java.util.Scanner; class Example { public static void main(String[ ] args) { FileInputStream fr = null; FileOutputStream fw = null; try { Scanner s = new Scanner(System.in); System.out.print("Enter source filename : "); String fileread = s.nextLine(); System.out.print("Enter destination filename : "); String filewrite = s.nextLine(); fr = new FileInputStream(fileread); fw = new FileOutputStream(filewrite); int a; do { a = fr.read(); char c = (char) a; fw.write(c); } while(a != -1); System.out.print(fileread + " content is copied to " + filewrite+"."); System.out.println(); } catch(FileNotFoundException e) { System.out.println("File doesnot exist."); } catch(IOException e) { System.out.println("Unable to read from specified file."); } catch(Exception e) { System.out.println(e); } finally { try { if(fr != null) { fr.close(); System.out.println("Source file closed."); } if(fw != null) { fw.close(); System.out.println("Destination file closed."); } } catch(IOException e) { System.out.println(e); } } } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then the source file will be open with the filename specified by user using keyboard if exists in the same directory in which the Example.java file is stored and the data will be stored in the destination file.*\

Output :

Enter source filename : Algo Enter destination filename : Valley Algo content is copied to Valley. Source file closed. Destination file closed. ABCD will be stored in Valley file.

Note :

Stream allows us to write or read different data by byte format. So, if we want to write or read a float, double etc. data then data may be lost.

Therefore to avoid the loss of data there is a concept of filter.


Filters :


DataOutputStream :-

The DataOutputStream class lets an application to write primitive data types to an output stream in portable way. The purpose of DataOutputStream class is to write the data between multiple machines which are located either in same network or in different network (remote writing).


Constructor for DataOutputStream :


DataOutputStream(OutputStream out) :-

This is constructor which is used to create a new data output stream to write data to the specified output stream.


Method for DataOutputStream :


void writeXxx(xxx value) :-

Here, xxx represents any fundamental data type. This method is used to write fundamental data into file.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileOutputStream f = new FileOutputStream("data1"); DataOutputStream d = new DataOutputStream(f); d.writeByte(65); d.writeShort(66); d.writeInt(67); d.writeLong(68); d.close(); f.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be generated by the name of data1 (if already exists then the data will be overwritten) in the same directory in which the Example.java file is stored and the data will be stored.*\

Output :

ABCD will be stored in data1 file.

DataInputStream :-

The DataInputStream class lets an application to read primitive data types from an input stream in portable way. The purpose of DataInputStream class is to read the data either from keyword or between multiple machines which are located either in same network or in different network (remote writing).


Constructor for DataInputStream :


DataInputStream(InputStream in) :-

This is constructor which is used to create a new data input stream to read data to the specified input stream.


Method for DataInputStream :


void readXxx(xxx value) :-

Here, xxx represents any fundamental data type. This method is used to read any type of fundamental data either from keyboard or from remote machine.


String readLine() :-

This method is used to read any type of data in the form of String type.

Example1 :

import java.io.*; class Example { public static void main(String[ ] args) { DataInputStream d = new DataInputStream(System.in); System.out.print("Enter first number : "); int a = Integer.parseInt(d.readLine()); System.out.print("Enter second number : "); int b = Integer.parseInt(d.readLine()); System.out.print("Sum of given number : "+(a+b)); } }

Output :

Enter first number : 10 Enter second number : 10 Sum of given number : 20

Example2 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileInputStream f = new FileInputStream("data1.txt"); DataInputStream d = new DataInputStream(f); byte b = d.readByte(); System.out.print(b + " "); short s = d.readShort(); System.out.print(s + " "); int i = d.readInt(); System.out.print(i + " "); long l = d.readLong(); System.out.print(l + " "); d.close(); f.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be opened by the name of data1 if exists in the same directory in which the Example.java file is stored.*\

Output :

65 66 67 68

Buffered Stream :

There are two types of Buffered Stream. They are :-

  • BufferedOutputStream




  • BufferedInputStream




The examples shown so far can be considered to be unbuffered I/O.

This means each read and write request is handle directly by the underlying OS.

This can make a program less efficient since each such request often triggers disk access, network activity or some other operations that are relatively expensive

To reduce this kind of overhead, Java Platform implements buffered I/O streams.

BufferedInputStream reads data from the memory is known as buffer and the native input API is called only when the buffer is empty.

Similarly the BufferedOutputStream writes data to the buffer and the native output API is called only when the buffer is full.

OS is performing following operation :-

  • Memory Management




  • I/O operation




  • Process Management




  • Device Management




BufferedOutputStream :-

The class implements a BufferedOutputStream by setting up such an output stream in which an application can write bytes to the underlying output stream.


Constructors for BufferedOutputStream class :


BufferedOutputStream(OutputStream out) :-

This constructor can create a new buffered output stream to write data to the specified underline output stream.


BufferedOutputStream(OutputStream out , int size) :-

This constructor can create a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.


Method in BufferedOutputStream class :


void flush() :

This method is used to flush the buffered output stream.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileOutputStream fw = new FileOutputStream("file3"); BufferedOutputStream b = new BufferedOutputStream(fw); b.write(65); b.write(66); b.write(67); b.write(68); b.close(); fw.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be generated by the name of file3 or if exists then overwritten in the same directory in which the Example.java file is stored and the output will be stored in that file.*\

Output :

ABCD will be stored in file3

Buffer writes the content to the file by underlying output stream in three cases :-

  • When buffer is full.

  • When flush() method invoked explicitly.

  • Before closing buffer.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileOutputStream fw = new FileOutputStream("file3"); BufferedOutputStream b = new BufferedOutputStream(fw , 2); b.write(65); b.write(66); b.write(67); b.write(68); b.flush(); b.close(); fw.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be generated by the name of file3 or if exists then overwritten in the same directory in which the Example.java file is stored and the output will be stored in that file.*\

Output :

ABCD will be stored in file3

BufferedInputStream :

BufferedInputStream adds functionality to another input stream which has the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created.


Constructor for BufferedInputStream class :


BufferedInputStream(InputStream in) :-

This constructor creates a buffered input stream and save its argument (InputStream in) for later use.


BufferedInputStream(InputStream in , int size) :-

This constructor creates a buffered input stream with the specified buffer size and save its argument (InputStream in) for later use.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileInputStream fw = new FileInputStream("file3"); BufferedInputStream b = new BufferedInputStream(fw , 2); int a; a = b.read(); System.out.print(a + " "); a = b.read(); System.out.print(a + " "); a = b.read(); System.out.print(a + " "); a = b.read(); System.out.print(a + " "); b.close(); fw.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example /*Then a file will be opened by the name of file3 if exists in the same directory in which the Example.java file is stored.*\

Output :

65 66 67 68 ABCD will be stored in file3

ByteArrayOutputStream :

This class implements an outstream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() method and toString() method. Closing a ByteArrayOutputStream has no effect. The method in this class can be called after the stream has been closed without generating an IOException.


Constructors for ByteArrayOutputStream class :


ByteArrayOutputStream() :-

This constructor creates a new byte array output stream.

ByteArrayOutputStream(int size) :-

This constructor creates a new byte array output stream with a buffer capacity of the specified size (in bytes).

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { ByteArrayOutputStream bs = new ByteArrayOutputStream(4); bs.write(65); bs.write(66); bs.write(67); bs.write(68); String s = bs.toString(); System.out.println(s); byte b[ ] = bs.toByteArray(); for(int i = 0 ; i < b.length ; i++) System.out.print(b[i] + " "); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

ABCD 65 66 67 68

ByteArrayInputStream :

ByteArrayInputStream contains an internal buffer that contain bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read() method. Closing a ByteArrayInputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.


Constructors for ByteArrayInputStream class


ByteArrayInputStream(byte[ ] buf) :-

This constructor creates a byte array input stream so that it uses buf as its buffer array.


ByteArrayInputStream(byte[ ] buf , int offset , int length) :-

This constructor creates a byte array input stream so that it uses buf as its buffer array. By this constructor we can read specific byte from an array by providing starting index and its length.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { byte b[ ] = {65 , 66 , 67 , 68}; ByteArrayInputStream bs = new ByteArrayInputStream(b); int a; a = bs.read(); System.out.print(a + " "); bs.skip(2); // this method will skip two index from byte b[ ] a = bs.read(); System.out.print(a + " "); bs.reset(); // this method will send cursor to first position i.e. b[0] a = bs.read(); System.out.print(a + " "); a = bs.read(); System.out.print(a + " "); a = bs.read(); System.out.print(a + " "); a = bs.read(); System.out.print(a + " "); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

65 68 65 66 67 68


X

MiniDoll :

MiniDoll is an application to learn with fun. You can play it to solve some tricky questions related to Java Programming. Either enjoy playing it alone or discuss with your friends to solve it. It is a simple approach to learn by solving questions. This application has different topics of Java and each topic is divided into three phases. Start solving from initial topic to final topic and by the end of every topic you can boost your concept of that topic.