Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Writer Class
Next article icon

Java Writer Class

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Java writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will use one of its concrete subclasses such as FileWriter, BufferedWriter, or PrintWriter.

Example 1: The below Java program demonstrates the working of the FileWriter class to write data to a text file.

Java
// Demonstrate the woking of FileWriter class import java.io.FileWriter; import java.io.IOException;  public class Geeks {     public static void main(String[] args)     {         try {                        // Create a FileWriter to write to a file named             // "example.txt"             FileWriter w = new FileWriter("example.txt");              // Write a simple message to the file             w.write("Hello, World!");              // Close the writer             w.close();              System.out.println(                 "Geeks for Geeks");         }         catch (IOException e) {             System.out.println("An error occurred: "                                + e.getMessage());         }     } } 

Output
Geeks for Geeks 

Declaration of the Writer Class

public abstract class Writer extends Object implements Appendable, Closeable, Flushable

Constructors of the Writer Class

The Writer class in Java has two protected constructors that allow for the creation of character streams with synchronization capabilities.

  1. Protected Writer(): Creates a new character stream that can itself synchronize on the writer.
  2. protected Writer(Object obj): Creates a new character stream that can itself synchronize on the given object – ‘obj’.

Java Writer Class Methods

There are certain methods associated with the Java Writer class as mentioned below:

1. write(int char) 

  • Itwrites a single character to the character stream.
  • Characters being written are contained in 16 lower bits of the 'char' integer value, the rest of the 16 higher bits are ignored by the method. 

Syntax:

public void write(int char)

  • Parameter: Theinteger value of the character to be written.
  • Return type: This method does not return any value
  • Exception: Throws IOException if an I/O error occurs during writing.

2. write(String str)

It writes a string to the character stream. 

Syntax:

public void write(String str)

  • Parameter: string to be written to the character stream.
  • Return type: This method does not return any value
  • Exception: Throws IOException if an I/O error occurs during writing.

3. write(String str, int offset, int maxlen) 

It writes some part of the string to the character stream. 

Syntax:

public void write(String str, int offset, int maxlen)

  • Parameter:
    • str: string to be written to the character stream.
    • offset: start position of the String
    • maxlen: maximum length upto which string has to written
  • Return type: This method does not return any value
  • Exception: Throws IndexOutOfBoundsException if the offset or maxlen is invalid, and IOException if an I/O error occurs.

4. write(char[] carray) 

It writes character array to the character stream. 

Syntax:

 public void write(char[] carray)

  • Parameter: Thecharacter array to be written to the character stream
  • Return type: This method does not return any value
  • Exception: Throws IOException if an I/O error occurs during writing.

5. write(char[] carray, int offset, int maxlen)

It writes some part of the character array to the character stream. 

Syntax:

public abstract void write(char[] carray, int offset, int maxlen)

  • Parameter:
    • carray: character to be written to the character stream
    • offset: start position of the character array
    • maxlen: maximum no. of the character of the carray has to written
  • Return type: This method does not return any value
  • Exception: Throws IndexOutOfBoundsException if the offset or maxlen is invalid, and IOException if an I/O error occurs.

6. close()

It closes the character stream, flushing it first. 

Syntax:

 public abstract void close()

  • Parameter: This method does not take any parameter.
  • Return type: This method does not return any value.
  • Exception: Throws IOException if an I/O error occurs during closing.

7. flush()

It flushes the Writer stream. Flushing one stream invocation will flush all other buffer in chain. 

Syntax:

public void flush()

  • Parameter: This method does not take any parameter.
  • Return type: This method does not return any value.
  • Exception: Throws IOException if an I/O error occurs while flushing.

8. append(char Sw)

It appends a single character to the Writer. 

Syntax:

public Writer append(char Sw)

  • Parameter: character to be append
  • Return type: This method return a writer.
  • Exception: Throws IOException if an I/O error occurs during appending.

9. append(CharSequence char_sq) 

It appends specified character sequence to the Writer. 

Syntax:

public Writer append(CharSequence char_sq)

  • Parameter: Character sequence to append.
  • Return type: This method return a writer, if char sequence is null, then NULL appends to the Writer.
  • Exception: Throws NullPointerException if the char_sq is null and IOException if an I/O error occurs during appending.

10. append(CharSequence char_sq, int start, int end)

It appends specified part of a character sequence to the Writer. 

Syntax:

public Writer append(CharSequence char_sq, int start, int end)

  • Parameter:
    • char_sq: Character sequence to append.
    • start: start of character in the Char Sequence
    • end: end of character in the Char Sequence
  • Return type: This method does not return value.
  • Exception: Throws IndexOutOfBoundsException if the start or end values are invalid, and IOException if an I/O error occurs.

Example 2: The below Java program demonstrates how to append individual character, entire sequence and substrings to the writer.

Java
// Java Program to demonstrates appending // Characters and String to the writer import java.io.*;  public class Main {     public static void main(String[] args)         throws IOException     {          // Writer to output to the console         Writer w = new PrintWriter(System.out);          System.out.println("Example 1: append(char)");          // Appending Characters         w.append('G');         w.append('e');         w.append('e');         w.append('k');         w.append('s');         w.flush();          System.out.println();          System.out.println(             "Example 2: append(CharSequence)");         CharSequence t = "Hello, Geeks!";          // Appending entire CharSequence         w.append(t);         w.flush();          System.out.println();          System.out.println(             "Example 3: append(CharSequence, start, end)");          // Appending substring "Hello"         w.append(t, 0, 5);         w.append(" ");          // Appending substring "Geeks"         w.append(t, 7, 12);         w.flush();          System.out.println();          // Close the writer         w.close();     } } 

Output
Example 1: append(char) Geeks Example 2: append(CharSequence) Hello, Geeks! Example 3: append(CharSequence, start, end) Hello Geeks 

Next Article
Java Writer Class

M

Mohit Gupta
Improve
Article Tags :
  • Java
  • Java-I/O
Practice Tags :
  • Java

Similar Reads

    Java Reader Class
    Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must ext
    6 min read
    Wrapper Classes in Java
    A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
    6 min read
    Nested Classes in Java
    In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
    5 min read
    Object Class in Java
    Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
    7 min read
    Static class in Java
    Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences