• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

IO-Streams In Java




IOSTREAMS
In java language stream represents flow of data.Whenever data is transferred from input device to java program is known as input stream and if the data is transferred from java program to output device is known as output stream.
In java language IO streams concept was introduced to handle input and output flow of data(especially with respective to files).
File:
File is a collection of information used to store data permanently.Every programming language bydefault supports temparary memory.But we want to store input or output data permanently it is recamended to used either file system or database.
Operation on files:
1.Open file
2.Writing data into file
3.Reading data from file
4.Close file

To perform above operations on file through java program some predefined classes are available in java.io package.These classes mainly catagerized into two types.
1.ByteStream classes
2.CharacterStream classes

ByteStream classes
These are set of classes used to write or read the data from or into the files in the form of binary values these are catagerized into following types.
Input stream classes
1.FileInputStream
2.DataInputStream
3.SequenceInputStream
4.ByteArrayInputStream
5.BufferedInputStream
6.ObjectInputStream

Note:
Used to read the data from the files in the form of binary values.
Output stream classes
1.FileOutputStream
2.DataOutputStream
3.ByteArrayOutputStream
4.BufferedOutputStream
5.ObjectOutputStream

Note:
Used to write the data into files in the form of binary values.
CharacterStream classes
Thsese are the set of classes used to perform either writing or reading operation from the files or into the files in the form of text.These are classified into following types.

Reader classes:
1.FileReader
2.CharacterArray classes
3.Buffered Reader classes

Note:
Used to read the data from a file in the form of text.
Writer classes
1.file writer
2.character array writer
3.buffered writer

Note:
Used to write the data from file in the form of text.

Key Points

Image






OutputStream Classes:

for all outputstream classes outpustream is predefined super class by using these classes we can able to write the data into files.
FileOutputStream: The main aim of this class is open the given file in a writing mode.
Syntax:
FileOutputStream fos=new FileOutputStream("File path");
If the file is available in the same location where the java program is accessble them directly filename with extension can be written otherwise complete path of the file should be written.
Example:
FileOutputStream fos=new FileOutputStream("abc.txt");
char x='A';
fos.write((int)x); -- used to write a single character into file
Note:
Using looping statements character by character can be written into a file.


import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream fos=new FileOutputStream("abc.txt");
fos.write(66);
}
}
Write the program to insert your name into a file

import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream fos=new FileOutputStream("abc.txt");
String s="sateesh";
int x,n;
n=s.length();
for(x=0;x<n;x++)
{
 fos.write((int)s.charAt(x)); 
}

}
}

Output:
DataOutputStream:

If we want to write a text value or statements into file at a time then it's recamended to use dataoutputstream class.
DataOutputStream dos=new DataOutputStream(fos);
String s="Hello msk Technologies";
dos.writeBytes(s); -- used to write a statements or string at a time into file.


import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner s=new Scanner(System.in);
System.out.print("Enter String");
String st=s.next();
FileOutputStream fos=new FileOutputStream("abc.txt");
DataOutputStream dos=new DataOutputStream(fos);
dos.writeBytes(st);
}
}
In the above Example writeBytes method is to write the data into file.
main throws an IOException that we can handle by using try-catch construction or that can throw from the JVM with the help of throws keyword.


Output:

ByteArrayOutputStream:

Which can be used to write the data of an array into file.
FileOutputStream fos=new FileOutputStream("abc.txt");
BytearrayOutputStream bos=new BytearrayOutputStream(fos);

byte b[];
...
... logic
...
bos.write(b);


import java.io.*;
class Main {
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("abc.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
for(int x=1;x<=100;x++)
{
bout.write(x);
}
bout.writeTo(fout1);
bout.close();
System.out.println("Success...");
}
}
Using ByteArrayOutputStream data can be transfer to a file with a faster rate.


Output:

BufferedOutputStream:

It is predefined class in java language.Whis is used to tranfer the data into file.
FileOutputStream fout = new FileOutputStream("abc.txt");
BufferedOutputStream bout = new BufferedOutputStream(fout);


import java.io.*;
class Main {
public static void main(String args[])throws Exception{
FileOutputStream fout = new FileOutputStream("abc.txt");
BufferedOutputStream bout = new BufferedOutputStream(fout);
byte b[] = {75, 76, 77, 78};
bout.write(b);
bout.close();
fout.close();
}
}
Using BufferedOutputStream data can be transfer to a file with a faster rate.


Output:

ObjectOutputStream:

Creates an ObjectOutputStream that writes to the specified OutputStream.
FileOutputStream fout = new FileOutputStream("file.txt");
ObjectOutputStream oots = new ObjectOutputStream(fout);


import java.io.*;
class Main {
public static void main(String args[])throws Exception{
FileOutputStream fout = new FileOutputStream("file.txt");
ObjectOutputStream oots = new ObjectOutputStream(fout);
String s =new String("Sateesh");
oots.writeObject(s);
oots.close();
}
}


Output:

InputStream Classes:

For all inputstream classes 'InputStream' is a predefined super class.

FileInputStream Class: Which is used to read the single character from the file.
FileInputStream fis=new FileInputStream("abc.txt");
In the above statement will open the file in reading mode.If the file is not available at given location an error will be generated.
int a=fis.read(); -- Read Single character form the file in the form of uni code.
System.out.println((char)a);


import java.io.*;
import java.util.*;
public class fileinputstreamDemo {
public static void main(String args[]) throws IOException
{
FileInputStream fis=new FileInputStream("abc.txt");
//System.out.println((char)fis.read()); one character
int i;
while((i=fis.read())!=-1)
{
System.out.println((char)i);
}
}
}


Output:

DataInputStream Class:

Which can be used to read a complete line or statement at a time from the file.
FileInputStream fis=new FileInputStream("abc.txt");
DataInputStream dis=new DataInputStream(fis);
System.out.println(dis.readLine()); -- It is used to read a line at a time.


import java.io.*;
import java.util.*;
public class DataInputStramDemo {
public static void main(String args[]) throws IOException
{
FileInputStream fis=new FileInputStream("abc.txt");
DataInputStream dis=new DataInputStream(fis);
String i;
while((i=dis.readLine())!=null)
{
System.out.println(i);
}
}
}


Output:

ByteArrayInputStream Class:

which can be used to read the data in the form of array.
FileInputStream fis=new FileInputStream("abc.txt");
ByteArrayInputStream bis=new ByteArrayInputStream(fis);
byte b[]=new byte[20];
for(int i=0;i<20; i++)
{
b[i]=bis.read();
System.out.println((char)b[i]);
}


import java.io.*;
class Main {
public static void main(String args[])throws Exception{
byte[] buf = { 35, 36, 37, 38 ,66,67,68};
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0;
while ((k = byt.read()) != -1)
{
char ch = (char) k;
System.out.println( k+ "= " + ch);
}
}
}


Output:

BufferedInputStream Class:

Which can be used to read the file information in the form of multiple buffers(arrays)
FileInputStream fis=new FileInputStream("abc.txt");
BufferedInputStream bfis=new BufferedInputStream(fis);
bfis.read();


import java.io.*;
class Main {
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("abc.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}
}


Output:

SequenceInputStream Class:

Which is used to read the data from multiple files in a sequencial order.any number of fileinputstream classes attached to SequenceInputStream.
FileInputStream fis1=new FileInputStream("abc.txt");
FileInputStream fis2=new FileInputStream("xyz.txt");
SequenceInputStream sis=new SequenceInputStream(fis1,fis2);
sis.read(); -- it will read the single character from the first file

OR

FileInputStream fis1=new FileInputStream("abc.txt");
FileInputStream fis2=new FileInputStream("xyz.txt");
SequenceInputStream sis=new SequenceInputStream(fis1,fis2);
DataInputStream dis=new DataInputStream(sis);
dis.readLine(); -- it will read the First Statement from the first file


import java.io.*;
import java.util.*;
public class SequenceInputStreamDemo {
public static void main(String args[]) throws IOException
{
FileInputStream fis1=new FileInputStream("abc.txt");
FileInputStream fis2=new FileInputStream("xyz.txt");
SequenceInputStream sis=new SequenceInputStream(fis1,fis2);
int i;
while((i=sis.read())!=-1)
{
System.out.println((char)i);
}
}
}


Using DataInputStream Classes import java.io.*;
import java.util.*;
public class SequenceInputStreamDemo {
public static void main(String args[]) throws IOException
{
FileInputStream fis1=new FileInputStream("abc.txt");
FileInputStream fis2=new FileInputStream("xyz.txt");
SequenceInputStream sis=new SequenceInputStream(fis1,fis2);
DataInputStream dis=new DataInputStream(sis);
String i;
while((i=dis.readLine())!=null)
{
System.out.println(i);
}
}
}


Output:

CharacterStream classes

Thsese are the set of classes used to perform either writing or reading operation from the files or into the files in the form of text.These are classified into following types.
Reader classes:
1.FileReader
2.CharacterArray classes
3.Buffered Reader classes
Writer classes
1.file writer
2.character array writer
3.buffered writer

1.FileReader:

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream



import java.io.FileReader;  
public class Main {  
    public static void main(String args[])throws Exception{    
          FileReader fr=new FileReader("abc.txt");    
          int i;    
          while((i=fr.read())!=-1)    
          System.out.print((char)i);    
          fr.close();    
    }    
}   




                

Output:

2.CharacterArray classes:

The CharArrayReader is composed of two words: CharArray and Reader. The CharArrayReader class is used to read character array as a reader (stream). It inherits Readerclass.



import java.io.CharArrayReader;  
public class Main{  
  public static void main(String[] ag) throws Exception {  
    char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' };  
    CharArrayReader reader = new CharArrayReader(ary);  
    int k = 0;  
    // Read until the end of a file  
    while ((k = reader.read()) != -1) {  
      char ch = (char) k;  
      System.out.print(ch + " : ");  
      System.out.println(k);  
    }  
  }  
}  





                

Output:

3.Buffered Reader classes:

Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class



import java.io.*;  
public class Main {  
    public static void main(String args[])throws Exception{    
          FileReader fr=new FileReader("abc.txt");    
          BufferedReader br=new BufferedReader(fr);    
  
          int i;    
          while((i=br.read())!=-1){  
          System.out.print((char)i);  
          }  
          br.close();    
          fr.close();    
    }    
}    






                

Output:

1.file writer:

Java FileWriter class is used to write character-oriented data to a file . It is character-oriented class which is used for file handling in java



import java.io.FileWriter;  
public class Main {  
    public static void main(String args[]){    
         try{    
           FileWriter fw=new FileWriter("abc.txt");    
           fw.write("Welcome to MSK Technologies.");    
           fw.close();    
          }catch(Exception e){System.out.println(e);}    
          System.out.println("Success...");    
     }    
}  






                

Output:

2.character array writer:

The CharArrayWriter class can be used to write common data to multiple files. This class inherits Writer class. Its buffer automatically grows when data is written in this stream. Calling the close() method on this object has no effect.



import java.io.CharArrayWriter;  
import java.io.FileWriter;  
public class Main {  
public static void main(String args[])throws Exception{    
          CharArrayWriter out=new CharArrayWriter();    
          out.write("Welcome to MSK Technologies");    
          FileWriter f1=new FileWriter("a.txt");    
          FileWriter f2=new FileWriter("b.txt");    
          FileWriter f3=new FileWriter("c.txt");    
          FileWriter f4=new FileWriter("d.txt");    
          out.writeTo(f1);    
          out.writeTo(f2);    
          out.writeTo(f3);    
          out.writeTo(f4);    
          f1.close();    
          f2.close();    
          f3.close();    
          f4.close();    
          System.out.println("Success...");    
         }    
        }    





                

Output:

3.buffered writer:

Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings



import java.io.*;  
public class Main {  
public static void main(String[] args) throws Exception {     
    FileWriter writer = new FileWriter("xyz.txt");  
    BufferedWriter buffer = new BufferedWriter(writer);  
    buffer.write("Welcome to MSK Technologies.");  
    buffer.close();  
    System.out.println("Success");  
    }  
}  





                

Output: