Home  >  Core Java

Java FileWriter and FileReader Example

By Arvind Rai, July 19, 2014
java.io.FileWriter and java.io.FileReader belongs to JDK 1.1. Character files are read and written using FileWriter and FileReader. Writing Streams of character is best suited using FileWriter.

FileWriter

FileWriter assumes that default character encoding and default byte-buffer size are appropriate. There are different constructors of FileWriter.
FileWriter(File file) : Accepts File Object
FileWriter(File file, boolean append) : Accepts File object and Boolean operator as true or false for append mode.
FileWriter(FileDescriptor fd) : Accepts FileDescriptor
FileWriter(String fileName) : File path as String
FileWriter(String fileName, boolean append) : File path as string and Boolean operator that allows for append mode.
FileWriterDemo.java
package com.cp.io;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
	public static void main(String[] args) throws IOException {
		CharArrayWriter out = new CharArrayWriter(); 
		out.write("Hello World!");
		FileWriter f = new FileWriter(new File("D:/cp/text.txt"));
		out.writeTo(f);
		out.close();
		f.close();
		System.out.println("Done");
	}
} 

FileReader

FileReader aslo assumes that default character encoding and default byte-buffer size are appropriate. FileReader reads character stream. The constructors are as below.
FileReader(File file) : Accepts File object
FileReader(FileDescriptor fd) : Accepts FileDescriptor object.
FileReader(String fileName) : Accepts file path as string.

FilterReaderDemo.java
package com.cp.io;
import java.io.BufferedReader;
import java.io.FileReader;
public class FilterReaderDemo {
	public static void main(String args[]) throws Exception { 
		FileReader fr = new FileReader("D:/cp/text.txt"); 
		BufferedReader br = new BufferedReader(fr); 
		String str; 
		while((str = br.readLine()) != null) { 
			System.out.println(str); 
		} 
		fr.close(); 
	} 
} 
Output will be Hello World!
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us