FileReader and FileWriter example program in Java

By Tamil Selvan Viewed: 32215 times Emailed: 318 times Printed: 478 times Bookmark and Share



FileReader

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.

The following example shows how to read lines from a file and print these to the standard output stream. It reads its own source file, which must be in the current directory.

// Demonstrate FileReader.
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}

FileWriter

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.

The following example is a character stream version of an example shown earlier when FileOutputStream was discussed. This version creates a sample buffer of characters by first making a String and then using the getChars( ) method to extract the character array equivalent. It then creates three files. The first, file1.txt, will contain every other character from the sample. The second, file2.txt, will contain the entire set of characters. Finally, the third, file3.txt, will contain only the last quarter.

// Demonstrate FileWriter.
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\\n"
+ " to come to the aid of their country\\n"
+ " and pay their due taxes.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
FileWriter f0 = new FileWriter("file1.txt");
for (int i=0; i < buffer.length; i += 2) {
f0.write(buffer[i]);
}
f0.close();
FileWriter f1 = new FileWriter("file2.txt");
f1.write(buffer);
f1.close();
FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.lengthbuffer.
length/4,buffer.length/4);
f2.close();
}
}




Comments(12)


1. the neccessary code to create website using java

By: haymanot girma at 2007-11-09 05:43:32
2. Very useful. Just a small comment on the line:
FileReader fr = new FileReader("FileReaderDemo.java");

Practically there is no need to read a java source file by a java program. It will look good if it's:
FileReader fr = new FileReader("FileReaderDemo.txt");

In any case, this example is very useful. Thanks for this.

By: Litty Joseph at 2008-02-06 08:37:52
3. thanks a lot that helped.. =D

By: Karthik at 2008-11-16 02:27:53
4. The example is awesome i found it most useful among all other sites

By: sabir pasha at 2009-01-20 05:11:34
5. excellent code.....

By: Anonymous at 2009-05-07 03:09:01
6. Where should the file be placed? How do I know what the "current directory" is? I'm using the typical Eclipse structure, with src and classes directories.

By: Anon at 2009-07-23 14:08:17
7. your code helps a lot.....
thanx......

By: beh at 2009-08-19 06:06:20
8. Nice example for FileReader and FileWriter,

The FileWriter code needed to be tweeked though,

FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.lengthbuffer.
length/4,buffer.length/4);
f2.close();

The f2.write(buffer,buffer.length/4,buffer.length/4) works
better, I couldn't find a method for FileWriter.write() that took
4 arguments....


By: Tim at 2009-10-21 17:31:00
9. Good Example ...For Both FIleWriter and FileReader..

By: karthikeyan.v at 2009-11-17 02:27:42
10. this s seems to be writing contents into a text file can i write into excel file using file writer class?

By: Iswariya at 2010-02-11 02:59:51
11. file reader is good but file writer is worst

By: sachinmani at 2010-03-01 04:34:22
12. nice example

By: pavang at 2010-07-20 01:16:22

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:


Enter Code:
The Captcha image

Latest Tutorials

[2010-09-02]Steps in using verisign certificate with Glassfish appserver
[2010-08-02]emulator 0 terminated while waiting for it to register!
[2010-08-02]Cannot run program "C:\Program Files\Java\jre6\bin\javac.exe": CreateProcess error=2, The system cannot find the file specified
[2010-08-01]Step by Step guide to setup freetts for Java
[2010-07-31]Speech Packages available for Java API
[2010-07-31]Tutorial on setting up freetts with maven
[2010-07-31]package com.sun.speech.freetts does not exist.
[2010-07-31]Text to Speech conversion program in Java
[2010-07-31]How to create wav file using freetts
[2010-07-31]How to set the width of a Text element in JavaFX?
[2010-07-31]Major components of FxObjects in JavaFX
[2010-07-03]Using the AWS SDK for Java in Eclipse
[2010-07-03]Using the AWS SDK for Java
[2010-01-01]Converting properties using PropertyEditors and Other Spring features worth mentioning
[2010-01-01]How to create an array and method in JSP

More Latest News

Most Viewed Articles (in last 30 days)
How to use ArrayList in Java
XML and Java - Parsing XML using Java Tutorial
How to use Iterator in Java
How to Send SMS using Java Program (full code sample included)
Using StringTokenizer in Java
Using substring( ) in Java
FileReader and FileWriter example program in Java
indexOf( ) and lastIndexOf( ) in Java
HashMap example in Java
wait(), notify() and notifyAll() in Java - A tutorial
Abstract classes in Java
compareTo( ) in Java
Method Overriding in Java
instanceof sample program in Java
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Most Emailed Articles (in last 30 days)
Components of program
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
Why java is important to the Internet
How to use ArrayList in Java
Execute system commands in a Java Program
FileReader and FileWriter example program in Java
Recursion in java
indexOf( ) and lastIndexOf( ) in Java
What is Java?
Method Overloading (function overloading) in Java
compareTo( ) in Java
Sample Java Script that displays a movable clock
History of Object
How to use Iterator in Java