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 Servlet Basics Servlet Basics Servlets are Java programs running on a web server that produce  results viewed remotely on a web server. Servlets has the same purpose that CGI or PHP had in the past.Here in this tutorial we … Read More
  • Income Tax Calculator With many of people giving Income tax each year this application would be a cool application for them as this will calculate their Income Tax in just few seconds. Its a java application. What you need to do is just change … 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
  • 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
  • Java: Declaring Your own Exceptions tutorial You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes: All exceptions must be a child of Throwable. If you want to write a checked exception that is automatic… Read More