StringWriter

Java StringWriter Example

In this example we are going to see how to use StringWriter. StringWriter is a subclass of java.io.Writer and can be used to write character streams in a String buffer and later can be used to obtain the stream as a String and even obtain the output buffer as a StringBuffer.

Let’s see some examples.
 
 
 
 
 

1. Using StringWriter

Let’s see how you can use StringWriter:

StringWriterExample.java:

package com.javacodegeeks.core.string;

import java.io.StringWriter;

public class StringWriterExample {

	public static void main(String[] args) {
		
		String str1 = "Hello World";
		String str2 =" of JavaCodeGeeks";
		
		StringWriter outputWriter = new StringWriter();
		outputWriter.write(str1);
		
		System.out.println(outputWriter.toString());

		outputWriter.write(str2);
		
		System.out.println(outputWriter.toString());

		outputWriter.append(" "+str1);

		System.out.println(outputWriter.toString());
	}
}

This will output :

Hello World
Hello World of JavaCodeGeeks
Hello World of JavaCodeGeeks Hello World

As you can see from the above example, we’ve basically used two StringWriter class methods : write and append which basically do the same thing, they append a string or a single character to the output stream (the string buffer). And then we’ve used toString to obtain the contents of the output buffer in the form of a String. Easy!

Let’s see another example. Here you can use write method to write a sub string of the output String:

StringWriterExample.java:

package com.javacodegeeks.core.string;

import java.io.StringWriter;

public class StringWriterExample {

	public static void main(String[] args) {
		
		String str1 = "Hello World";
		String str2 =" of JavaCodeGeeks";
		
		StringWriter outputWriter = new StringWriter();
		
		outputWriter.write(str1,0,8);
		
		System.out.println(outputWriter.toString());
	}
}

This will output :

Hello Wo

2. Obtain the StringBuffer

Here you can see how you can obtain and use the output buffer of the StringWriter in the form of a StringBuffer.

StringWriterExample.java:

package com.javacodegeeks.core.string;

import java.io.StringWriter;

public class StringWriterExample {

	public static void main(String[] args) {
		
		String str1 = "Hello World";
		String str2 =" of JavaCodeGeeks";
		
		StringWriter outputWriter = new StringWriter();
		
		outputWriter.write(str1,0,8);
		
		System.out.println(outputWriter.toString());
		
		StringBuffer sbuf = outputWriter.getBuffer();
				
		sbuf.append(str2);

		System.out.println(outputWriter.toString());
	}
}

This will output :

Hello Wo
Hello Wo of JavaCodeGeeks

As you can see you can obtain the StringBuffer and use it normally. The changes will be reflected in the StringWriter.

3. A simple use case

Here we are going to present a simple use case of StringWriter. In this example we are going to read file and convert its contents to String.

Let’s see how :

StringWriterExample.java:

package com.javacodegeeks.core.string;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class StringWriterExample {

	public static void main(String[] args) throws IOException {
		
		String str1 = stringWriter("F:\\nikos7\\Desktop\\s.txt");
		System.out.println(str1);
	}
	
	public static String stringWriter(String fileName) throws IOException {

        char[] buff = new char[1024];
        Writer stringWriter = new StringWriter();
        FileInputStream fStream = null;
        Reader bReader = null;

        try {

            fStream = new FileInputStream(fileName);
            bReader = new BufferedReader(new InputStreamReader(fStream, "UTF-8"));
            int n;
            while ((n = bReader.read(buff)) != -1) {
                stringWriter.write(buff, 0, n);
            }
        } finally {
        	bReader.close();
            stringWriter.close();
            fStream.close();
        }
        return stringWriter.toString();
    }
}

Ok so in the above program we simple open a file and read chunks of 1024 characters of it at a time. We then write these characters in the StringWriter. When the loop ends we use toString to convert the character stream that we’ve read into a String.

Download Source Code

This was a Java StringWriter Example. You can download the source code of this example here : StringWriterExample.zip

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button