Friday, November 4, 2011

Reading and Writing File in Java

Posted by on Friday, November 4, 2011 Read our previous post
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 :


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

            File f=new File("5tH.txt");
            FileReader fl=new FileReader(f);
            BufferedReader bf=new BufferedReader(fl);
            //For reading till end
        }catch(Exception e){
            System.out.println("Error : " );

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 :


class FWriting { 

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

        String source = "";
        FileWriter f0 = new FileWriter("file1.txt");
        BufferedReader bf=new BufferedReader(new InputStreamReader(;
        //For writing new Content Everytime you run
                f0.write(source + System.getProperty("line.separator"));
        //For appending the content
              f0.append(source+ System.getProperty("line.separator"));    


© 2010 Code 2 Learn