top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are FileReader and FileWriter ? Explain with an example to read and write into files.

0 votes
351 views
What are FileReader and FileWriter ? Explain with an example to read and write into files.
posted Mar 17, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The FileReader and FileWriter are two classes which are used to read character data from files in case of reading and into file in case of writing.Both classes used for file handling purpose in java and these are character oriented.
In FileWriter class you have: as constructor :
FileWriter(String file) which creates a new file. It gets file name in string and FileWriter(File file) which creates a new file. It gets file name in File object.
See this example where we are writing data into a file named "QueryHomeUserDetails.txt"

class QueryHomeUserDetails{  
 public static void main(String args[]){  
  try{  
   FileWriter fileWriter=new FileWriter("QueryHomeUserDetails.txt");  
   fileWriter.write("UserName: shivamkrpandey@live.com,Education:MCA ,College: Dept CS,ISc,BHU");  
   fileWriter.close();  
  }catch(Exception exception){
         System.out.println(exception);
     }  
  System.out.println("Written successfully");  
 }  
}  

In FileReader class it returns data in byteformat.Here is the example of file reading from the file "QueryHomeUserDetails.txt".

class QueryHomeUserDetails{  
 public static void main(String args[])throws Exception{  
  FileReader fileReader=new FileReader("QueryHomeUserDetails.txt");  
  int line;
  while((line=fileReader.read())!=-1)      //read() method which returns a character in ASCII form. It returns -1 at the end of file.
  System.out.println((char)line);  
  fileReader.close();   //closes FileReader.
 }  
}  

After reading it results:
UserName: shivamkrpandey@live.com,Education:MCA ,College: Dept CS,ISc,BHU

answer Mar 19, 2016 by Shivam Kumar Pandey
...