Tuesday, 29 August 2017

Java Program to Read and write a file using FileReader and FileWriter

Read and write a file using FileReader and FileWriter. (Character Stream)

Program

import java.io.*;
import java.util.Scanner;
public class ReaderWriter {
    public static void main(String args[])
    {
        try
        {
            FileWriter fw= new FileWriter(args[0]);
            for(int i=0;i<12;i++)
            {
                fw.write("Line : " +i + "\n");
            }
            fw.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
             try
             {                       
                  String Str;
                             Scanner in = new Scanner(System.in);
                             System.out.println("Enter File name:");
                             Str = in.nextLine();
                       FileReader fr= new FileReader(Str);
            int i;
            while((i=fr.read())!=-1)
                             System.out.print((char)i);
            fr.close();
                   }
        catch(Exception e)
        {
            e.printStackTrace();
        }
          }

}

Output


0 comments:

Post a Comment