Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 PipedWriter Class
Next article icon

Java.io.OutputStreamWriter Class

Last Updated : 28 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, OutputStreamWriter class connects character streams to byte streams. It encodes Characters into bytes using a specified charset. 

Declaration of Java OutputStreamWriter Class 

public class OutputStreamWriter
extends Writer

Constructors of OutputStreamWriter Class in Java

Constructors in OutputStreamWriter are mentioned below:

  • OutputStreamWriter(OutputStream geek_out) : Creates a “geek_out” OutputStreamWriter that uses 
    default charset for encoding.
  • OutputStreamWriter(OutputStream geek_out, Charset geek_set): Creates a “geek_out” OutputStreamWriterthat uses a “geek_ set” charset for encoding.
  • OutputStreamWriter(OutputStream geek_out, CharsetEncoder encode): Creates a “geek_out” OutputStreamWriter that uses a given encoder.
  • OutputStreamWriter(OutputStream geek_out, String setName): Creates a “geek_out” OutputStreamWriter that uses a named character set.

Methods of OutputStreamWriter Class in Java

Method 

Description

flush()flushes the stream
close()closes the flushed stream
write(int char)writes a single character.
write(String geek, int offset, int strlen)            writes a portion of the “geek” string starting from “offset position” upto “strlen” length.
write(char[] geek, int offset, int strlen)writes a portion of the “geek” character array starting from “offset position” upto “strlen” length.
getEncoding()tells the name of the character encoding being used in the mentioned Stream.

1. flush() : 

java.io.OutputStreamWriter.flush() flushes the stream. 

Syntax : public void flush()

Parameters :
------

Return :
void

Exception :
-> IOException : if in case anu I/O error occurs.

2. close() : 

java.io.OutputStreamWriter.close() closes the flushed stream. 

Syntax : public void close()

Parameters :
------

Return :
void

Exception :
-> IOException : if in case anu I/O error occurs, e.g writing after closing the stream

3. write(int char) :

java.io.OutputStreamWriter.write(int char) writes a single character. 

Syntax : public void write(int char)

Parameters :
char : character to be written

Return :
void

Example:

Java
// Java code explaining the working of write(int char), // flush(), close() import java.io.*;  // Driver Class public class NewClass {     // Main Function     public static void main(String[] args)     {         try {             // Creation of new OutputStreamWriter             OutputStream g                 = new FileOutputStream("test.txt");             OutputStreamWriter geeks_out1                 = new OutputStreamWriter(g);              // Creating an Input Stream             FileInputStream in                 = new FileInputStream("test.txt");              // Use of write(int char) :             // Writing character values to the "test.txt"             geeks_out1.write(71);             geeks_out1.write(69);             geeks_out1.write(69);             geeks_out1.write(75);             geeks_out1.write(83);              // flush the stream             geeks_out1.flush();              // read what we write             for (int i = 0; i < 5; i++) {                 // Reading the content of "test.txt" file                 System.out.println("write(int char) : "                                    + (char)in.read());             }             geeks_out1.close();         }         catch (Exception ex) {             System.out.println("Error");             ex.printStackTrace();         }     } } 

Output :  

write(int char) : G
write(int char) : E
write(int char) : E
write(int char) : K
write(int char) : S

4. write(String geek, int offset, int strlen) :

java.io.OutputStreamWriter.write(String geek, int offset, int strlen) writes a portion of the “geek” string starting from “offset position” upto “strlen” length. 

Syntax :public void write(String geek, int offset, int strlen)

Parameters :
geek : string whose portion is to be written
offset : starting position from where to write
strlen : length upto which we need to write

Return :
void

Exception :
-> IOException : if in case any I/O error occurs.

Example:

Java
// Java code explaining the working of write(String geek, // int offset, int strlen)) import java.io.*;  // Driver Class public class NewClass {     // main Function     public static void main(String[] args)     {         String geek = "GEEKSForGeeks";         try {             // Creation of new OutputStreamWriter             OutputStream g                 = new FileOutputStream("test.txt");             OutputStreamWriter geeks_out1                 = new OutputStreamWriter(g);              // Creating an Input Stream             FileInputStream in                 = new FileInputStream("test.txt");              // Use of write(String geek, int offset, int             // strlen)) : Writing character values to the             // "test.txt"             geeks_out1.write(geek, 4, 9);              // flush the stream             geeks_out1.flush();              // read what we write             for (int i = 0; i < 5; i++) {                 // Reading the content of "test.txt" file                 System.out.println("write(int char) : "                                    + (char)in.read());             }             geeks_out1.close();         }         catch (Exception ex) {             System.out.println("Error");             ex.printStackTrace();         }     } } 

Output :  

write(int char) : S
write(int char) : F
write(int char) : o
write(int char) : r
write(int char) : G

5. write(char[] geek, int offset, int strlen) :

java.io.OutputStreamWriter.write(char[] geek, int offset, int strlen) writes a portion of the “geek” character array starting from “offset position” upto “strlen” length. 

Syntax : public void write(char[] geek, int offset, int strlen)

Parameters :
geek : character array whose portion is to be written
offset : starting position from where to write
strlen : length upto which we need to write

Return :
void

Exception :
-> IOException : if in case anu I/O error occurs.

6. getEncoding() :

java.io.OutputStreamWriter.getEncoding() tells the name of the character encoding being used in the mentioned Stream. 
If there is predefined name exists, then it is returned otherwise the canonical name of the encoding is returned. 
Returns Null, if the stream has been already closed. 

Syntax : public String getEncoding()

Parameters :
------

Return :
Name of the charset encoding used

Exception :
-> IOException : if in case anu I/O error occurs.
Java
// Java code explaining write(char[] geek, int offset, int // strlen) and getEncoding() method import java.io.*;  // Driver Class public class NewClass {     // Main Function     public static void main(String[] args)     {         char[] geek = { 'G', 'E', 'E', 'K', 'S' };         try {             // Creation of new OutputStreamWriter             OutputStream g                 = new FileOutputStream("test.txt");             OutputStreamWriter geeks_out1                 = new OutputStreamWriter(g);              // Creating an Input Stream             FileInputStream in                 = new FileInputStream("test.txt");              // Use of write(char[] geek, int offset, int             // strlen)) : Writing character values to the             // "test.txt"             geeks_out1.write(geek, 0, 3);              // flush the stream             geeks_out1.flush();              // read what we write             for (int i = 0; i < 3; i++) {                 // Reading the content of "test.txt" file                 System.out.println(                     "char[] geek, int offset, int strlen) : "                     + (char)in.read());             }              // get and print the encoding for this stream             System.out.println("\nName of the charset : "                                + geeks_out1.getEncoding());              // Closing the OutputStreamWriter             geeks_out1.close();         }          catch (Exception ex) {             System.out.println("Error");             ex.printStackTrace();         }     } } 

Output :  

char[] geek, int offset, int strlen) : G
char[] geek, int offset, int strlen) : E
char[] geek, int offset, int strlen) : E
Name of the charset : UTF8 


Next Article
Java PipedWriter Class

M

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

Similar Reads

  • Java.io.OutputStream class in Java
    This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
    2 min read
  • Java.io.Writer class in Java
    This abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.
    4 min read
  • Java.io.StringWriter class in Java
    Java StringWriter class creates a string from the characters of the String Buffer stream. Methods of the StringWriter class in Java can also be called after closing the Stream as this will raise no IO Exception. Declaration in Java StringWriter Classpublic class StringWriter extends WriterConstructo
    6 min read
  • Java PipedWriter Class
    The PipedWriter class in Java allows two threads to communicate with each other by passing data through a pipe. This class is useful when we want one part of the program to send data to another part without storing it in memory. Features of the PipedWriter Class: It allows writing data into a pipe.I
    6 min read
  • Java Writer Class
    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 u
    5 min read
  • Java.io.ObjectOutputStream Class in Java | Set 1
    An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. Only objects that support the java.io.Serializable in
    9 min read
  • Java.io.ObjectInputStream Class in Java | Set 1
    ObjectInputStream Class deserializes the primitive data and objects previously written by ObjectOutputStream. Both ObjectOutputStream and ObjectInputStream are used as it provides storage for graphs of object.It ensures that the object it is working for, matches the classes of JVM i.e Java Virtual M
    9 min read
  • Java.io.ObjectInputStream Class in Java | Set 2
    Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStrea
    6 min read
  • Java PushbackReader Class
    The PushbackReader class in Java is part of the java.io.package, and is used for reading characters from a stream. This class lets us push characters back into the stream. Features of PushbackReader Class: This class uses a buffer that allows us to push characters back into the stream.This class is
    6 min read
  • Java.io.PipedInputStream class in Java
    Pipes in IO provides a link between two threads running in JVM at the same time. So, Pipes are used both as source or destination. PipedInputStream is also piped with PipedOutputStream. So, data can be written using PipedOutputStream and can be written using PipedInputStream.But, using both threads
    5 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