StringWriter in Java

A character stream that collects its output in a string buffer, which can then be used to construct a string.
Closing a StringWriter has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

Constructors

StringWriter in Java

Methods

Screen Shot 2020-04-05 at 5.45.38 PM

package com.java.io;

import java.io.IOException;
import java.io.StringWriter;

public class StringWriterExample {

    public static void main(String[] args) {

        StringWriter stringWriter = null;
        try {
            stringWriter = new StringWriter();
            stringWriter.write(" data1 ");
            stringWriter.write(" data2 ");
            stringWriter.write(" data3 ");
            String data = stringWriter.toString();
            StringBuffer dataBuffer = stringWriter.getBuffer();
            System.out.println("data:" + data);
            System.out.println("dataBuffer:" + dataBuffer);

        } finally {
            // Closing the streams
            if (stringWriter != null)
                try {
                    stringWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }

}
data: data1 data2 data3 
dataBuffer: data1 data2 data3

Related Article

Java I/O Basics

Leave a Reply

Your email address will not be published. Required fields are marked *