freetimestudys@gmail.com          +91-7097633380
  Login Here                        

BufferedReader and BufferedWriter

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

It is character-oriented class which is used for file handling in java.

BufferedReader program

import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\test.txt");
fw.write("Welcome to freetimestudy.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}  

intput and output

output:Success...

BufferedWriter program

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

intput and output

output:Welcome to freetimestudy

copy of file by using BufferedReader and BufferedWriter

import java.io.*;
class Test
{
static BufferedReader br;
static BufferedWriter bw;
public static void main(String[] args)
{
try{
br=new BufferedReader(new FileReader("so.java"));
bw=new BufferedWriter(new FileWriter("de.java"));
String str;
while ((str=br.readLine())!=null)
{
bw.write(str);
}
br.close();
bw.close();
}
catch(Exception e)
{
System.out.println("getting Exception");
}
}
}

intput and output

output:copy so.java to de.java

Java.util.Scanner reading file

import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args)
{
try{
Scanner s=new Scanner(new BufferedReader(new FileReader("abc.txt")));
while (s.hasNext())
{
System.out.println(s.next());
}
}
catch(Exception e)
{
System.out.println(e);
System.out.println("getting Exception");
}
}
}

intput and output

output:Welcome to freetimestudy