All for Joomla All for Webmasters

Java FileWriter and FileReader (File Handling in java)

Java FileWriter and FileReader classes are used to write and read data from text files. These are character-oriented classes, used for file handling in java.

Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to read and write the textual information.


Java FileWriter class

Java FileWriter class is used to write character-oriented data to the file.

Constructors of FileWriter class

Constructor Description
FileWriter(String file) creates a new file. It gets file name in string.
FileWriter(File file) creates a new file. It gets file name in File object.

Methods of FileWriter class

Method Description
1) public void write(String text) writes the string into FileWriter.
2) public void write(char c) writes the char into FileWriter.
3) public void write(char[] c) writes char array into FileWriter.
4) public void flush() flushes the data of FileWriter.
5) public void close() closes FileWriter.

Java FileWriter Example

In this example, we are writing the data in the file abc.txt.

  1. import java.io.*;
  2. class Simple{
  3.  public static void main(String args[]){
  4.   try{
  5.    FileWriter fw=new FileWriter(“abc.txt”);
  6.    fw.write(“my name is sachin”);
  7.    fw.close();
  8.   }catch(Exception e){System.out.println(e);}
  9.   System.out.println(“success”);
  10.  }
  11. }

Output:

success...

Java FileReader class

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.

Constructors of FileWriter class

Constructor Description
FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn’t exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn’t exist, it throws FileNotFoundException.

Methods of FileReader class

Method Description
1) public int read() returns a character in ASCII form. It returns -1 at the end of file.
2) public void close() closes FileReader.

Java FileReader Example

In this example, we are reading the data from the file abc.txt file.

  1. import java.io.*;
  2. class Simple{
  3.  public static void main(String args[])throws Exception{
  4.   FileReader fr=new FileReader(“abc.txt”);
  5.   int i;
  6.   while((i=fr.read())!=-1)
  7.   System.out.println((char)i);
  8.   fr.close();
  9.  }
  10. }

Output:

my name is sachin
PinIt
submit to reddit

Leave a Reply

Top