Java Write


Java Writer

It is an abstract class to write to the character streams. write(char[], int, int), flush(), and close() are the methods that a subclass must implement. Many subclasses will override some of the methods defined to provide higher efficiency, functionality or both.

Different methods are provided by the Writer class, which are implemented by its subclasses. Here are a few examples of techniques:

  • write(char[] array) - Send the output stream the characters from the provided array
  • write(String data) – It writes to the Writer the supplied string
  • append(char c) - the requested character is inserted into the current Writer
  • flush() - causes all data in the Writer to be written to the relevant destination
  • close() - the writer concludes

Constructors of Java Writer:

  • protected Writer (): This function creates a new character stream that can synchronize with the Writer.
  • protected Writer(Object obj): Creates a new character stream that can synchronize with the specified object ('obj').

Essential notes about Java Writer:

  • Writing an array of characters to a Java Writer is faster than writing a single character. The increase in speed can be enormous, up to 10 times or more. As a result, whenever practical, the write(char[]) methods should be used.
  • Wrapping a Java Writer in a Java BufferedWriter provides transparent buffering of bytes written to it. All bytes written to the BufferedWriter are first buffered in the BufferedWriter's internal byte array. When the buffer is filled, it is flushed all at once to the underlying Writer.

Example :

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

OUTPUT:

Success…