StringWriter

In this chapter you will learn:

  1. How to use StringWriter
  2. Use StreamTokenizer to read StrngReader

Use StringWriter

StringWriter is character stream that collects its output in a string buffer.

import java.io.IOException;
import java.io.StringWriter;
/*from   j  a  v  a 2 s  . c o m*/
public class Main {
  public static void main(String args[]) throws IOException {
    StringWriter outStream = new StringWriter();
    String s = "This is a test from j a va2s.com.";
    for (int i = 0; i < s.length(); ++i)
      outStream.write(s.charAt(i));
    System.out.println("outstream: " + outStream);
    System.out.println("size: " + outStream.toString().length());
  }
}

The output:

outstream: This is a test from j a va2s.com.
size: 33

Use StreamTokenizer to read StrngReader

The following code creates a StringWriter from a string and uses StreamTokenizer to read word by word.

import java.io.StreamTokenizer;
import java.io.StringReader;
//from j  a  va2 s .  c o m
public class Main {
  public static void main(String[] args) throws Exception{
    StringReader reader = new StringReader("this is a test");

    int wordCount = 0;
    StreamTokenizer streamTokenizer = new StreamTokenizer(reader);

    while (streamTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
      if (streamTokenizer.ttype == StreamTokenizer.TT_WORD)
        wordCount++;
    }
    System.out.println("Number of words in file: " + wordCount);
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use PrintWriter
  2. Append to a file with PrintWriter
  3. Turn off the auto flush on PrintWriter
  4. How to extend PrintWriter to create your own Writer
Home » Java Tutorial » Reader Writer
Stream vs Reader and writer
InputStream
FileInputStream
ObjectInputStream
DataInputStream
BufferedInputStream
SequenceInputStream
PushbackInputStream
ByteArrayInputStream
PrintStream
OutputStream
FileOutputStream
DataOutputStream
ObjectOutputStream
BufferedOutputStream
ByteArrayOutputStream
FilterOutputStream
Reader
FileReader
BufferedReader
CharArrayReader
StringReader
LineNumberReader
InputStreamReader
PushbackReader
Writer
FileWriter
BufferedWriter
CharArrayWriter
StringWriter
PrintWriter
OutputStreamWriter