Comments

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 :


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();

         } 
}

© 2010 Code 2 Learn