11/4/11

Reading and Writing File in Java

Java like other programming languages supports both reading and writing of files. For reading purpose we use FileReader and for writing we use FileWriter.


FileReader Class :

The FileReader class creates a Reader that you can use to read the contents of a file. Its two most commonly used constructors are shown here:

FileReader(String filePath) 
FileReader(File fileObj)



Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file.


Example :


import java.io.*;

public class FReading {
    public static String str="";
    
    public static void main(String[] args) {

        try{
            File f=new File("5tH.txt");
            FileReader fl=new FileReader(f);
            BufferedReader bf=new BufferedReader(fl);
            //For reading till end
            while((str=bf.readLine())!=null){
                System.out.println(str);
            }
        f1.close();
        }catch(Exception e){
            System.out.println("Error : " );
            e.printStackTrace();
        }
    }
}


FileWriter Class :

FileWriter creates a Writer that you can use to write to a file. Its most commonly used constructors are shown here:

FileWriter(String filePath)  
FileWriter(String filePath, boolean append)

FileWriter(File fileObj)

They can throw an IOException or a SecurityException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, then output is appended to the end of the file.

Creation of a FileWriter is not dependent on the file already existing. FileWriter will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown.

Example :

import java.io.*; 

class FWriting { 

    public static void main(String args[]) throws Exception { 

        String source = "";
        FileWriter f0 = new FileWriter("file1.txt");
        BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
        //For writing new Content Everytime you run
        while(!(source=bf.readLine()).equalsIgnoreCase("q")){
                f0.write(source + System.getProperty("line.separator"));
                
        }
        //For appending the content
        while(!(source=bf.readLine()).equalsIgnoreCase("q")){
              f0.append(source+ System.getProperty("line.separator"));    
        }
        f0.close();

         } 
}

SHARE THIS POST:

Related Posts:

  • OOPs Concept : Inheritance After discussing Encapsulation, now its time for 'Inheritance' as OOP Concept. Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is … Read More
  • OOPs Concept : Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any java object that can pass more t… Read More
  • Public static void main(String args[]){} : Explained public static void main(String args[]){ } Now lets understand why do we write the above statement, the way it is written above.  Why not change it? Before we move to the topic make sure you understand the Keywo… Read More
  • Java Tutorial : What is a Class? Java class is nothing but a template for object you are going to create or it’s a blue print by using this we create an object. In simple word we can say it’s a specification or a pattern which we define and every object we… Read More
  • Good Practices : Programming Tips Java One of the Good practices while programming using Java is listed below. Consider Static Factory Methods instead of Constructors The normal way for a client to obtain an instance of itself is to provide a public const… Read More