CodesJava

Easy learning with example program codes

FileReader and FileWriter in java

FileReader:

FileReader class is used for reading streams of characters from a file.

Commonly used constructors of FileReader:

1. FileReader(File file)

Creates a new FileReader, given the File to read from.

2. FileReader(String fileName)

Creates a new FileReader, given the name of the file to read from.

Example:

FileReaderExample.java

import java.io.FileReader;
 
/**
 * This program is used to read a file using FileReader.
 * @author codesjava
 */
class IOTest{
	public void readFile(){
		try {
			//creating FileReader object.
			FileReader fr = 
                         new FileReader("F:\\New folder\\data1.txt");
 
			int i;
			//read file.
			while((i=fr.read())!=-1){
				System.out.print((char)i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
public class FileReaderExample {
	public static void main(String args[]){
		//creating IOTest object.
		IOTest obj = new IOTest();
 
		//method call.
		obj.readFile();
	}
}

Output:

Hello.
This is a text file.

Download this example.

FileWriter:

FileWriter  class is used for streams of characters to a file.

Commonly used constructors of FileWriter:

1. FileWriter(File file)

Creates a FileWriter object given a File object.

2. FileWriter(String fileName)

Creates a FileWriter object given a file name.

Example:

FileWriterExample.java

import java.io.FileWriter;
 
/**
 * This program is used to write data into 
 * a file using FileOutputStream.
 * @author codesjava
 */
class IOTest{
	String str = "Hello www.codesjava.com";
 
	public void writeFile(){
		try {
		  //Creating FileWriter object.
		  //It will create a new file before writing if not exist.
		  FileWriter fw = 
                       new FileWriter("F:\\New folder\\data6.txt");
		   fw.write(str); 
		   fw.flush();
		   //Close file after write operation.
		   fw.close();  
 
		   System.out.println("Contents written successfully.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
public class FileWriterExample {
	public static void main(String args[]){
		//Creating IOTest object.
		IOTest obj = new IOTest();
 
		//method call
		obj.writeFile();
	}
}

Output:

Contents written successfully.

Download this example.
 
Next Topic: How To Check If A File Exists In Java.
Previous Topic: BufferedInputStream and BufferedOutputStream in java with example.

 

Please follow and like us:
error
Posted in IO   








Copyright © 2019 CodesJava DMCA.com Protection Status