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:

  • Java : Using JDBC API Tutorial You need to use database drivers and the JDBC API while developing a Java application to retrive or store data in a database. The JDBC API classes and interfaces are available in the java.sql  and the javax.sql  … Read More
  • OOPs Concept: Encapsulation Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. RFAZHE7YNFV8 Encapsulation is the technique of making the fields in a class private and provid… Read More
  • Java Programming with Eclipse : Basics This is intended to be a basic guide to using Eclipse. This guide is by no means comprehensive, but is sufficient to give you enough knowledge to work on your projects. Running and using Ecli… Read More
  • Create Linked List using Java The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure. It has the two constructors, shown here: RFAZHE7YNFV8 Link… Read More
  • Java Modifiers Summary The Modifier class provides static methods and constants to decode class and member access modifiers. The sets of modifiers are represented as integers with distinct bit positions representing different modifiers. … Read More