Java StringWriter ClassLast Updated : 29 Jan 2026 Java StringWriter class is used to write character data into an internal string buffer, which can later be converted into a String. In this chapter, we will understand what the StringWriter class is, why it is used, its declaration, constructors, methods, and examples to see how character data can be collected and processed in memory. What is StringWriter Class in Java?The StringWriter class is a character stream that collects written output in an internal StringBuffer. This buffered content can later be converted into a String using the toString() method. The StringWriter class extends the Writer class and works entirely in memory. Since it does not use system resources such as files or network sockets, calling the close() method on a StringWriter object has no effect. Java StringWriter class declarationThe StringWriter class is a part of the java.io package and extends the Writer class. Constructors of StringWriter ClassThe StringWriter class provides constructors to create a character output stream that writes data into an internal string buffer. 1. StringWriter()This constructor creates a new StringWriter using a default initial buffer size. Syntax: Here is the syntax: 2. StringWriter(int initialSize)This constructor creates a new StringWriter using the specified initial buffer size. Syntax: Here is the syntax: Example of StringWriter Class ConstructorsThe following example demonstrates how to create a StringWriter object using its constructors. Methods of StringWriter classThe StringWriter class provides several methods to write character data and retrieve it as a string.
Examples of Java StringWriter ClassPractice the following examples to understand and usages of StringWriter class. Example 1: Reading File Data into StringWriterThe following example demonstrates how to use StringWriter to read file data into memory and convert it into a string. Here, we are assuming that testout.txt contains the following data: Javatpoint provides tutorial in Java, Spring, Hibernate, Android, PHP etc. Output: Javatpoint provides tutorial in Java, Spring, Hibernate, Android, PHP etc. Example 2: Writing Data Directly Using StringWriterThe following example demonstrates how to write data directly into a StringWriter and retrieve it as a String. Output: Welcome to Java StringWriter class. Next TopicJava StringReader Class |
We request you to subscribe our newsletter for upcoming updates.