Open In App

Writer write(String) method in Java with Examples

Last Updated : 24 Oct, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The write method of the Writer class is used to write a specified string to a character stream. It is commonly used for writing text to files, consoles, or other character-based outputs.

  • Writes the entire content of the given string to the stream.
  • Requires explicit flushing (e.g., flush()) to ensure data is written when using buffered writers.

Syntax

public void write(String string)

  • Parameters: This method accepts a mandatory parameter
  • Return Value: This method does not return any value.
  • Exceptions: Throws IOException if an I/O error occurs.

Example 1: Writing a Full String to Console

Java
import java.io.*;

class GFG{
    
    public static void main(String[] args) {
        try{
            
            // Create a Writer instance that writes to console
            Writer writer = new PrintWriter(System.out);

            // Write the String 'GeeksForGeeks' to the stream
            writer.write("GeeksForGeeks");

            // Flush the stream to ensure data is printed
            writer.flush();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output
GeeksForGeeks

Explanation: The string "GeeksForGeeks" is written to the console, and flush() ensures the data appears immediately.

Example 2: Writing a Short String to Console

Java
import java.io.*;

class GFG{
    
    public static void main(String[] args){
        
        try {
            
            // Create a Writer instance that writes to console
            Writer writer = new PrintWriter(System.out);

            // Write the String 'GFG' to the stream
            writer.write("GFG");

            // Flush the stream to ensure data is printed
            writer.flush();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output
GFG

Explanation: The string "GFG" is written to the console, demonstrating that write(String) works for any length of string.

Why Use write(String)?

  • Allows writing text to files, consoles, or other character-based streams.
  • Gives control over when data is sent to the destination using flush().
  • Essential for handling character streams efficiently in Java applications.



Explore