freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Buffered Streams

   Up to we are working with non buffered streams these are providing less performance because these are interact with the hard disk, network.
  Now we have to work with Buffered Streams
   BufferedInputStream read the data from memory area known as Buffer.
We are having four buffered Stream classes
   1. BufferedInputStream
   2. BufferedOutputStream
 

BufferedOutputStream create and write file

import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testtxt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to freetimestudy.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success...........");
}
}  

intput and output

output:success...........

BufferedInputStream read the file

import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\test.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}

intput and output

output:Wecome to freetimestudy

copy of file

import java.io.*;
class Test
{
static BufferedInputStream bis;
static BufferedOutputStream bos;
public static void main(String[] args)
{
try{
bis=new BufferedInputStream(new FileInputStream("abc.txt"));
bos=new BufferedOutputStream(new FileOutputStream("xyz.txt"));
int str;
while ((str=bis.read())!=-1)
{
bos.write(str);
}
bis.close();
bos.close();
}
catch(Exception e)
{
System.out.println(e);
System.out.println("getting Exception");
}
}
}

intput and output

output:copy abc.txt to xyz.txt