FileReader and FileWriter example program in Java

By: Tamil Selvan Viewed: 281449 times  Printer Friendly Format    


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



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. the neccessary code to create website using java
View Tutorial          By: haymanot girma at 2007-11-09 05:43:32

2. Very useful. Just a small comment on the line:

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

3. thanks a lot that helped.. =D
View Tutorial          By: Karthik at 2008-11-16 02:27:53

4. The example is awesome i found it most useful amon
View Tutorial          By: sabir pasha at 2009-01-20 05:11:34

5. excellent code.....
View Tutorial          By: Anonymous at 2009-05-07 03:09:01

6. Where should the file be placed? How do I know wh
View Tutorial          By: Anon at 2009-07-23 14:08:17

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

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

8. Nice example for FileReader and FileWriter,

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

9. Good Example ...For Both FIleWriter and FileReader
View Tutorial          By: karthikeyan.v at 2009-11-17 02:27:42

10. thats copied from
"Java the Complete

View Tutorial          By: Daniel at 2010-01-20 03:01:34

11. this s seems to be writing contents into a text fi
View Tutorial          By: Iswariya at 2010-02-11 02:59:51

12. file reader is good but file writer is worst
View Tutorial          By: sachinmani at 2010-03-01 04:34:22

13. I NEED A JAVA CODE TO CREATE THE EMPTY FILE AND PR
View Tutorial          By: HEMA at 2010-06-04 09:52:25

14. Thanks very helpful.
I learned about filere

View Tutorial          By: Nelson at 2010-06-18 06:40:26

15. nice example
View Tutorial          By: pavang at 2010-07-20 01:16:22

16. Check a cool file reader
View Tutorial          By: John at 2010-09-13 01:38:21

17. useful for me
View Tutorial          By: ganga at 2010-10-06 00:48:52

18. useful for me
View Tutorial          By: ganga at 2010-10-06 00:51:51

19. Is it possible to create a Reader class without lo
View Tutorial          By: bs at 2010-10-11 05:42:34

20. Is it possible to create a Reader class without lo
View Tutorial          By: bs at 2010-10-11 05:43:42

21. Simple file writer example. .............
<

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

22. hi everbody. i need to extract a output from one j
View Tutorial          By: keerthi at 2010-10-29 13:38:28

23. Quite a use guidelines...good samples..both FileRe
View Tutorial          By: Debender Prasad at 2010-11-01 06:25:24

24. how to read byte code from file
View Tutorial          By: Manthan at 2011-01-17 09:38:15

25. well an easy code to understand
thanks muc

View Tutorial          By: narmada at 2011-01-17 09:47:01

26. well an easy code to understand
thanks muc

View Tutorial          By: narmada at 2011-01-17 09:47:01

27. well an easy code to understand
thanks muc

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

28. Hi everybody.i m new to java.dont know how to deve
View Tutorial          By: saranya at 2011-01-31 22:40:17

29. wow! thats nice, java program can read and write t
View Tutorial          By: Mutare at 2011-02-25 22:58:09

30. hi ! that's a great code anyway.. but can someone
View Tutorial          By: mart at 2011-03-01 03:40:34

31. grazie!!!
View Tutorial          By: Egidio De Lorenzo at 2011-04-20 12:07:25

32. very useful
View Tutorial          By: Ruchika at 2011-07-10 05:15:05

33. its useful code.
but i want to write in a f

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

34. Excellent site.
View Tutorial          By: anonymous at 2011-11-06 12:07:14

35. i WROTE A FILE READER LIKE IT WAS IN THE SAMPLE BU
View Tutorial          By: LILI at 2011-11-06 01:47:20

36. Simpler example:

import java.io.*;

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

37. The actual code to write F2 is:
f2.write(bu

View Tutorial          By: João at 2012-04-11 19:20:51

38. The actual code to write F2 is:
f2.write(bu

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

39. hi I am getting error while running this program a
View Tutorial          By: sampada at 2012-04-18 07:45:19

40. It's work perfectly.Good job.
Thank u very

View Tutorial          By: BlackVirus at 2012-05-18 05:29:28

41. Can any help me to get Second line,Second word in
View Tutorial          By: Ramesh at 2012-07-21 11:09:53

42. Can any help me to get Second line,Second word in
View Tutorial          By: Ramesh at 2012-07-21 11:12:05

43. THE FILE READER ONLY READS ONE LINE! HELP!!! REPLY
View Tutorial          By: PLEASE READ THIS!!! at 2012-09-03 14:07:12

44. sir, thanks sir. very help to me. its simple and e
View Tutorial          By: kannathasan.M at 2012-10-01 07:59:28

45. Thank you,

But this only solves my

View Tutorial          By: Raju at 2012-12-13 10:01:38

46. FYI, if you're using NetBeans, the input file shou
View Tutorial          By: pberg at 2013-03-28 17:00:16

47. Nice and helpful tutorial.
But it gives err

View Tutorial          By: Wasim at 2013-12-10 05:00:32

48. how to read csv file using Java
View Tutorial          By: Shireesha at 2013-12-26 07:34:22

49. Thanks! Very helpful in creating a program i am tr
View Tutorial          By: BHaos at 2014-12-05 16:32:53

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

51. FileWriter and FileReader class is used to for rea
View Tutorial          By: Roy at 2015-12-05 06:30:44

52. Reliable Packers and Movers in Pune @
http

View Tutorial          By: Rohit at 2016-02-24 08:02:58

53. my family was searching for Form cbt 200 tc severa
View Tutorial          By: David Blanchett at 2016-09-21 13:56:39

54. it did not help me please fix it !!!!!!!!!
View Tutorial          By: joiiiiiii at 2016-10-04 09:31:25

55. eonufajoq
View Tutorial          By: eonufajoq at 2017-01-26 12:42:00

56. utopemoro
View Tutorial          By: utopemoro at 2017-01-26 12:50:16

57. orojumoi
View Tutorial          By: orojumoi at 2017-01-26 12:59:51

58. selumuqo
View Tutorial          By: selumuqo at 2017-01-27 01:44:39

59. You suck at coding, atleast follow the GNU coding
View Tutorial          By: Nibba at 2017-03-29 05:15:21

60. JasonNix
View Tutorial          By: JasonNix at 2017-04-24 19:31:29

61. Hi!....I want to need for open .docx file in text
View Tutorial          By: ragupathi at 2017-05-25 20:13:20

62. I must say you have very interesting content here.
View Tutorial          By: 89Swen at 2017-06-20 06:09:10

63. I see your website needs some fresh content. Writi
View Tutorial          By: BlytheX at 2017-06-22 05:08:15

64. Hello, i think that i saw you visited my site thus
View Tutorial          By: alquiler barco mallorca particular at 2017-08-13 07:21:52

65. unonuiutomu
View Tutorial          By: unonuiutomu at 2017-08-15 11:25:45

66. ewidehapidebc
View Tutorial          By: ewidehapidebc at 2017-08-15 12:10:52

67. epuvipiaqmon
View Tutorial          By: epuvipiaqmon at 2017-08-15 12:32:01

68. otideheva
View Tutorial          By: otideheva at 2017-08-16 03:31:09

69. can u plz send me the 5 employee details program i
View Tutorial          By: chandan at 2017-08-28 08:17:19