FileReader and FileWriter example program in Java

By: Tamil Selvan Emailed: 1698 times Printed: 2196 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(34)


1. View Comment

the neccessary code to create website using java

View Tutorial          By: haymanot girma at 2007-11-09 05:43:32
2. View Comment

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.


View Tutorial          By: Litty Joseph at 2008-02-06 08:37:52
3. View Comment

thanks a lot that helped.. =D

View Tutorial          By: Karthik at 2008-11-16 02:27:53
4. View Comment

The example is awesome i found it most useful among all other sites

View Tutorial          By: sabir pasha at 2009-01-20 05:11:34
5. View Comment

excellent code.....

View Tutorial          By: Anonymous at 2009-05-07 03:09:01
6. View Comment

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.

View Tutorial          By: Anon at 2009-07-23 14:08:17
7. View Comment

your code helps a lot.....
thanx......


View Tutorial          By: beh at 2009-08-19 06:06:20
8. View Comment

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....


View Tutorial          By: Tim at 2009-10-21 17:31:00
9. View Comment

Good Example ...For Both FIleWriter and FileReader..

View Tutorial          By: karthikeyan.v at 2009-11-17 02:27:42
10. View Comment

this s seems to be writing contents into a text file can i write into excel file using file writer class?

View Tutorial          By: Iswariya at 2010-02-11 02:59:51
11. View Comment

file reader is good but file writer is worst

View Tutorial          By: sachinmani at 2010-03-01 04:34:22
12. View Comment

nice example

View Tutorial          By: pavang at 2010-07-20 01:16:22
13. View Comment

Check a cool file reader

View Tutorial          By: John at 2010-09-13 01:38:21
14. View Comment

useful for me

View Tutorial          By: ganga at 2010-10-06 00:51:51
15. View Comment

Is it possible to create a Reader class without looking for File in physical location. I have a File object which I got it from cache and I want to construct Reader class, when constructing it should not look in to physical path of file because I already removed the file from directory to test the cache. any idea?

View Tutorial          By: bs at 2010-10-11 05:42:34
16. View Comment

Simple file writer example. .............

import java.io.BufferedWriter;
import java.io.FileWriter;

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

FileWriter fw = new FileWriter("mytest.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("test2");
bw.close();
fw=null;

}
}


View Tutorial          By: Chezhian TK at 2010-10-14 21:40:16
17. View Comment

hi everbody. i need to extract a output from one java program and generate it into word document. please help me with code. i need to do it on tomo

View Tutorial          By: keerthi at 2010-10-29 13:38:28
18. View Comment

well an easy code to understand
thanks much


View Tutorial          By: narmada at 2011-01-17 09:47:02
19. View Comment

Hi everybody.i m new to java.dont know how to develop a project.can anybody help me?

View Tutorial          By: saranya at 2011-01-31 22:40:17
20. View Comment

wow! thats nice, java program can read and write to a file easily compare to C and C++

View Tutorial          By: Mutare at 2011-02-25 22:58:09
21. View Comment

grazie!!!

View Tutorial          By: Egidio De Lorenzo at 2011-04-20 12:07:25
22. View Comment

very useful

View Tutorial          By: Ruchika at 2011-07-10 05:15:05
23. View Comment

its useful code.
but i want to write in a file which is already a written txt file but i want to add at some specific location such as after 100 lines or so. what changes i would need to make for this same scenario for the reading that i want to read from specific line number
help me
thanks in advance


View Tutorial          By: SARWAR at 2011-08-02 06:26:37
24. View Comment

i WROTE A FILE READER LIKE IT WAS IN THE SAMPLE BUT STILL CAN COMPILE IT, CAN SOMEONE HELP
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();
}
}


View Tutorial          By: LILI at 2011-11-06 01:47:20
25. View Comment

Excellent site.

View Tutorial          By: anonymous at 2011-11-06 12:07:14
26. View Comment

Simpler example:

import java.io.*;
class WriteToText {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men to come to the aid of their country and pay their due taxes.";
FileWriter f0 = new FileWriter("file1.txt");
f0.write(source);
f0.close();
}
}


View Tutorial          By: Joseph Harner at 2011-12-04 23:20:48
27. View Comment

The actual code to write F2 is:
f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);
f2.close();

Because here you "say"
Write the buffer.
Starting from buffer.length-buffer.length/4
= 96-(96/4) = 96-24 = 72.
Than it will start after the 72tah char of buffer.

And finally write buffer.length/4 = (24 chars)


View Tutorial          By: João at 2012-04-11 19:22:14
28. View Comment

hi I am getting error while running this program as below
C:\Program Files\Java\jdk1.6.0_07\bin>javac FileWirterDemo.java
FileWirterDemo.java:9: cannot find symbol
symbol : constructor FileWriter(java.lang.String)
location: class FileWriter
FileWriter f0 = new FileWriter("file1.txt");
^
FileWirterDemo.java:11: cannot find symbol
symbol : method write(char)
location: class FileWriter
f0.write(buffer[i]);
^
FileWirterDemo.java:13: cannot find symbol
symbol : method close()
location: class FileWriter
f0.close();
^
FileWirterDemo.java:14: cannot find symbol
symbol : constructor FileWriter(java.lang.String)
location: class FileWriter
FileWriter f1 = new FileWriter("file2.txt");
^
FileWirterDemo.java:15: cannot find symbol
symbol : method write(char[])
location: class FileWriter
f1.write(buffer);
^
FileWirterDemo.java:16: cannot find symbol
symbol : method close()
location: class FileWriter
f1.close();
^
FileWirterDemo.java:17: cannot find symbol
symbol : constructor FileWriter(java.lang.String)
location: class FileWriter
FileWriter f2 = new FileWriter("file3.txt");
^
FileWirterDemo.java:18: cannot find symbol
symbol : variable lengthbuffer
location: class char[]
f2.write(buffer,buffer.lengthbuffer.
^
FileWirterDemo.java:18: cannot find symbol
symbol : method write(char[],int,int)
location: class FileWriter
f2.write(buffer,buffer.lengthbuffer.
^
FileWirterDemo.java:20: cannot find symbol
symbol : method close()
location: class FileWriter
f2.close();
^
.\FileWriter.java:22: cannot find symbol
symbol : constructor FileWriter(java.lang.String)
location: class FileWriter
FileWriter fstream = new FileWriter(file_name);
^
11 errors


View Tutorial          By: sampada at 2012-04-18 07:45:19
29. View Comment

Can any help me to get Second line,Second word in some file,by using the FileReader class methods.

Assume that ex.txt file is there :
hai how are you?
im Ramesh from bec.
___________________

i need output : Ramesh


View Tutorial          By: Ramesh at 2012-07-21 11:12:05
30. View Comment

sir, thanks sir. very help to me. its simple and easy.

View Tutorial          By: kannathasan.M at 2012-10-01 07:59:28
31. View Comment

FYI, if you're using NetBeans, the input file should be located in the project's root directory/folder.

View Tutorial          By: pberg at 2013-03-28 17:00:16
32. View Comment

how to read csv file using Java

View Tutorial          By: Shireesha at 2013-12-26 07:34:22
33. View Comment

Thanks! Very helpful in creating a program i am trying to make.

View Tutorial          By: BHaos at 2014-12-05 16:32:53
34. View Comment

lllllllllllllllllllllllllllllike

View Tutorial          By: duck at 2015-04-10 19:19:47

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Tamil Selvan
Inner Class Example in Java
PreparedStatement Example in Java
UNIX read and write system calls sample program in C
Pointer Arrays and Pointers to Pointers in C
Relational and Logical Operators in C
Arithmetic Operators in C
strlen() sample program in C++
Sample program to draw a arc in J2ME
What Java Has Removed from C++
FileReader and FileWriter example program in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
InetAddress Example program in Java
XML and Java - Parsing XML using Java Tutorial
Inheritance Example in Java
Type Casting in Java
Simple Port Scanner application using Java
right shift operator, >>, in Java
Garbage collection and Finalize() method
Read from a COM port using Java program
Abstract classes in Java
Integer: byte, short, int, and long data types in Java
Student marks calculation program in Java
Calculate gross salary in Java
Stack example in Java - push(), pop(), empty(), search()
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Most Emailed Articles (in Java)
Write to a COM port using Java program
How to use ArrayList in Java
Java program for changeable wrapper class
History of Java
Data Types in Java
Sample program to demonstrate the use of ActionListener
Introducing JavaScript.
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Student marks calculation program in Java
Vector in Java - Sample Program
Save/Write/Read image file from/to a database using Java program
How to access instance from an inner class and accessing outer class variables in java
Method Override sample in Java
Using jar utility in Java - A jar tutorial