Monday, April 16, 2012

File Reader and File Writer

FileReader and FileWriter
This will helps you to understand the reading and writing concept of file.
Sample:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class FileReaderAndWriter {

      public static void main(String args[]) throws Exception {
            String path = "D:/Hello.txt";
            File file = new File(path);
            writeFile(file, " Write this.", true);
            readFile(file);
      }

      public static void readFile(File file) throws Exception {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String s = null;
            while ((s = br.readLine()) != null) {
                  System.out.println(s);
            }
            br.close();
            fr.close();
      }
     
      public static void writeFile(File file, String text, boolean append) throws Exception {
            FileWriter fw = new FileWriter(file, append);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(text);
            bw.close();
            fw.close();
      }    
}

No comments:

Post a Comment