In this tutorial, we will learn about how to implement Input stream classes, Output stream classes, Reader stream classes, Writer stream classes, Buffered Input Stream classes, Buffered Output Stream classes and File System Operations in java along with suitable examples.
- To learn the file handling concepts in java follow the steps given below :
- I/O Streams : – Java streams are classified into two basic types input stream and output stream. An input stream extracts (i.e. reads) data from the source (i.e. file) and sends it to the program. Similarly an output stream takes data from the program and sends (i.e. writes) it to the destination (file).
- Input Stream : Input stream classes are used to read 8-bit bytes include a super class called as InputStream and a number of subclasses for supporting various input related functions. Below figure shows the class hierarchy of input stream classes.
- readShort()
- readBoolean()
- readint()
- readChar()
- readLong()
- readLine()
- readFloat()
- readDouble()
- readUTF()
- Output Stream : Output stream classes are derived from the base class OutputStream. Like InputStream, the OutputStream is an abstract class and we cannot instantiate it. The several subclasses of the OutputStream can be used for performing the output operations.
Below figure shows the class hierarchy of output stream classes.
Some output stream methods are below : –
The DataOutputStream, that is similar of DataInputStream, implements the interface DataOutput, so it implements the following methods contained in DataOutput interface.
- writeShort()
- writeBoolean()
- writeInt()
- writeLong()
- writeFloat()
- writeDouble()
- writeUTF()
- writeChar()
- writeBytes()
Example : This example shows how InputStream and OutputStream are used in java class.
import java.io.*; class InputOutputStreamEx { public static void main(String []args)throws IOException {//write text with space and characters String source = "Now is the time for all good men\n"+ "to come to the aid of their country\n"+"and pay their due taxes."; //declare variables int lines=0,char1=0,c=0,words =0; //declare temporary variable as true boolean temp=true; String whitespace =" \t\n\r"; //create object fos and write text into mno.txt file OutputStream fos = new FileOutputStream("mno.txt"); //define byte array b and source into getByte() byte b[] = source.getBytes(); //call method fos write fos.write(b); //fos close fos.close(); System.out.println("File Created "); //read from mno.txt file InputStream fis = new FileInputStream("mno.txt"); while((c=fis.read()) != -1)//check condition { char1 ++;//increment char1 by 1 if(c=='\n')//check condition { lines ++;//increment line by 1 } /*The index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur*/ int index = whitespace.indexOf(c); if(index == -1) { if(temp==true)//check condition { ++words;//increment word by 1 } temp=false; } else { temp=true; } } if(char1 != 0)//check condition { ++ lines;//increment by 1 } System.out.println("Number of lines: " +lines + "\n Number of Characters :" +char1+ "\n Number of words: " +words); } }
Output :
File Created Number of lines: 3 Number of Characters: 93 Number of words: 21
- Readers and Writers : – Character stream classes that provide support for managing I/O operation on characters. These classes can be used to read and write 16-bit Unicode characters. There are two kinds of character stream classes’ reader stream classes and writer stream classes.
- Reader Stream Classes : These classes are used to read character from the files. Reader class is the super class for all other Reader classes. These classes are functionally very similar to the input stream classes, except input stream use bytes, while reader stream use characters. The Reader class is used for handled characters, so reader classes can perform all the functions implemented by the input stream classes.
- Writer Stream Classes : The writer stream classes are used to perform all output operations on files. Only difference is that while output stream classes are used for write bytes, the writer stream classes are designed to write characters. The Writer class is an abstract class which acts as a super class for all the other writer stream classes. This super class provides support for all output operations by defining methods that are exact to those in OutputStream class.
Hierarchy of writer stream classes: –
- Buffered Streams : – This class provides default methods for the bulk of the functions in the User Defined Streams protocol. The user needs to define only the methods stream-read-buffer, stream-write-buffer and stream-element-type for each subclass of buffered stream, so the default methods implement buffered I/O.
- Buffered Input Streams : – In java.io package two streams exist in byte streams category for buffering BufferedInputStream and BufferedOutputStream. These classes are subclasses of FilterInputStream and FilterOutputStream and these are used to increase the performance with buffer by functionality. BufferedInputStream is much faster for larger data amounts and disk access. An internal buffer array is created, when the BufferedInputStream is created.
It has two constructors: –
i. BufferedInputStream(InputStream inputStream)
ii. BufferedInputStream(InputStream inputstream, int bufSize) - Buffered Output Stream : – It is used to provide buffering to your output stream. It is also provides much faster disk access and larger data amounts. Buffer is nothing but the reserved memory block. With buffer we can write whole block of data at once.
It has two constructors: –i. BufferedOutputStream(OutputStream out)
ii. BufferedOutputStream(OutputStream out, int size)It inherits all methods from the FileOutputStream, few methods below: –
a.write(byte b): – Write the specified byte to the buffered output stream
b.write (byte [] b, int i, int j): – Write j bytes from the specified byte array starting at i to the buffered output stream.
c.flush(): – Is used for flushes the buffered output stream
d.close() - File System operations : –
- canRead (): – Check whether the application can read the file.
- canWrite (): – : – Check whether the application can modify the file.
- createNewFile (): – : – – Check whether the application can modify the file.
- delete(): – : – Delete the file or directory.
- exists(): – : – Check whether the file or directory exists.
- getAbsolutePath (): – : –Return the absolute pathname in string.
- isDirectory (): – : –Check whether the file is a directory or not.
- isHidden (): – : –Check whether the file is a hidden file or not.
- list(): – : – Returns an array of strings naming the files and directories in the directory.
Fig.a) Reading data into a program Fig.b) Writing data to a destination.
Java provides two kinds of byte stream classes; input stream classes and output stream classes.
The super class InputStream is an abstract class and we cannot create instances of super class. So we must use the subclasses that inherit from super class. Note that the class DataInputStream extends FilterInputStream and implements the interface DataInput. So in this case the DataInputStream class implements the methods described in DataInput in addition to using the methods of InputStream class. The DataInput interface contains the below methods : –
The InputStream class defines methods for performing input functions.
Some input stream methods are given below: –
Hierarchy of reader stream classes: –
Example : This example shows how to File Reader and Writer Stream classes are used in java.
import java.io.*; public class FileReadWriteEx { public static void main(String[] args) { try { //read from 123.txt file FileReader flr = new FileReader("123.txt"); //write into abc.txt file FileWriter flw = new FileWriter("abc.txt"); int i;//create temporary variable while((i = flr.read())!=-1)//check condition { flw.write(i); System.out.println((char)i); } flw.close(); flr.close(); }//if file not found then throws an exception catch (FileNotFoundException e) { System.out.println("File Not Exist.."+e.getMessage()); } catch (Exception e) { System.out.println("Some I/O Problem."+e.getMessage()); } } }
Example : This example shows how to BufferedInputStream and BufferedOutputStream are used in java class.
import java.io.*; public class InputStream { public static void main(String[] args) throws IOException { //here create object of FileInputStream and read from abc.txt file FileInputStream fis = new FileInputStream("abc.txt"); //Here store abc.txt file into BufferedInputStream object bis BufferedInputStream bis = new BufferedInputStream(fis); //here creating new file mno.txt FileOutputStream fos = new FileOutputStream("mno.txt"); BufferedOutputStream bos = new BufferedOutputStream(fos); int temp;//here we create temporary variable while((temp=bis.read())!=-1)//check condition read from bis up to end of text. { //copy from temp and write into bos bos.write(temp); //display onto console System.out.println((char)temp); } bos.close();//close bos fos.close();//close fos bis.close();//close bis fis.close();//close fis } }
Example : This example shows how to File System Operations is used in java class.
import java.io.File; public class FileOperationsExamp { public static void main(String[] arg) { try { File file = new File ("file name"); //Check whether the application can read the file System.out.println (file.canRead ()); //Check whether the application can modify the file System.out.println (file.canWrite ()); //Check whether the application can modify the file System.out.println (file.createNewFile ()); //Delete the file or directory System.out.println (file.delete ()); //Check whether the file or directory exists. System.out.println (file.exists ()); //Returns the absolute pathname string. System.out.println (file.getAbsolutePath ()); //Check whether the file is a directory or not. System.out.println (file.isDirectory ()); //Check whether the file is a hidden file or not. System.out.println (file.isHidden ()); //Returns an array of strings naming the //files and directories in the directory. System.out.println (file.list ()); } catch (Exception e) { e.printStackTrace (); } } }
Output :
false false true true false D:\Priyanka\PriyaJava\18+19-08-2014\file name false false null
Hence, in this tutorial we successfully learnt about how to implement Input stream classes, Output stream classes, Reader stream classes, Writer stream classes, Buffered Input Stream classes, Buffered Output Stream classes and File System Operations in java along with suitable examples.