Monday, 3 June 2019

Know more About the Java Filewriter Class with Examples


In detail, the Java FileWriter class is generally used to write character-oriented data to a file. Besides, this is a character-oriented class which is used to handle file in Java smoothly. Different from File Output Stream class, there is no need to convert the strings into a byte array. The reason behind this is Java File Writer provides an easy method to write the string directly. Let’s know more about Java FileWriter.



·      This class is a major part of Java.io package.
·      File writer is the subclass of Java.io Output Stream Writer Class.
·     The File Writer is meant for writing the streams of characters.
·    This is widely used to write character files. It’s written () method lets you write charter (s) or the string to the file.

·    The higher-level Writer objects generally wrap the File Writers. For example, BufferedWriter or PrintWriter. Such Java File Writer provides a better performance, higher-level, and different flexible methods to write important data.

Methods of using File writer

1.      Public Void Write (int c) gives IO Exception- It writes a single character.

2.      Public Void Write (Char [] stir) gives IOException – It writes an array of characters.

3.      Void Write (String Str) gives IO Exception- This writes a string.

4.      Public Void File Write (String Str. Int off. Int Len) gives IO Exception- It creates a part of the string. However, the of is offset, and from there, you will have started writing the characters. Len is the number of characters to write.

5.      Public Void Flush () gives IO Exception- It flushes the stream

6.      Public Void Close () gives IO Exception- It provides the stream first and after that closes the Java File Writer.

Example of Java FileWriter
In this example, you can learn about how to write the data ion the testout.txt file using Java File Writer class.

package com.javatpoint; 
import java.io.FileWriter; 
public class FileWriterExample { 
public static void main (String args[]){   
try {
FileWriterfw=new FileWriter("D:\\testout.txt");  
fw.write("Welcome to javaTpoint.");   
w.close();   
} catch (Exception e) {System.out.println(e);}   
System.out.println("Success...");   
}   
} 

Understand the File output Stream and File Writer Stream

·         The File Writer is designed to write stream of characters while the File Output Stream is generally used to write raw bytes streams.

·         The File Writer deals with the 16-bit characters. But the FileOutputStream works with 8-bit bytes.
·         The File Writer can easily handle Unicode strings. On the other hand, File Output Stream does not accept characters or strings.