--- title: File IO Operation in Java date: 2012-06-27 14:25:44 categories: - Codes tags: - code-example - java --- The following is a simple example on how to read & write data from a file. For Writing data we need following objects ``` File Object -> FileWriter Object -> PrintWriter Object ``` For Reading data we need following objects ``` File Object -> FileReader Object -> BufferedReader Object ``` #### Expected Output ![File IO Operation in Java Output](/images/java_file_io_output.jpg) #### WriteReadDemo.java ```java package com.rohansakhale.ioprogram; import java.io.*; /** * * @author Rohan Sakhale */ public class WriteReadDemo { public static void main(String[] args) throws Exception{ // Lets create an object for writing data onto a file // For that we will need object in following manner // File -> FileWriter -> BufferedWriter -> PrintWriter // PrintWriter will do all the job of writing data onto file String filePath = "1rohan_test.txt"; // The best way to get the default directory of system // for windows it chooses desktop for writing this file File file = new File(filePath); FileWriter fw = new FileWriter(file); // fw tends to throw IOException BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw, true); // true states to flush automatically // if not set true you can use following line whenever you need to flush // pw.flush(); pw.println("Rohan testing file writing"); pw.println("Using PrintWriter Class"); // The above lines should write data to file. // For Vista & Seven users, make sure to select the path with file writable permissions // Over here I used, My Documents path for file writing // Lets read the written content from file onto console now // For that you will need the following objects // File -> FileReader -> BufferedReader // we will use the same file object as above FileReader fr = new FileReader(file); // fr tends to throw IOException BufferedReader br = new BufferedReader(fr); String str = br.readLine(); // Reads the entire one line of text at once while(str != null) // Checks if the string being read is not null { System.out.println(str); str = br.readLine(); // Runs untill it does not reach end of file. } // Closing the opened string bw.close(); br.close(); pw.close(); } } ```