StringBufferInputStream Example


StringBufferInputStream Example: As in the earlier program, where the source of reading is a byte array in case of ByteArrayInputStream, now the source is a string buffer in case of StringBufferInputStream. That is, StringBufferInputStream reads from a string buffer (or the other way, string).

StringBufferInputStream class methods and constructors are deprecated (observe the compiler message in screen shot). Designers observed problems in converting characters to bytes. Designers favor character stream StringReader for StringBufferInputStream.

Buffering and read string StringBufferInputStream
The following program on StringBufferInputStream Example illustrates the reading of strings using StringBufferInputStream.
import java.io.*;
public class SBIDemo
{
  public static void main(String args[]) throws IOException
  {
    String comments = "Improve\nthe\ncontent\nwith\nyour\nvalueble\ncomments";
    StringBufferInputStream sbis = new StringBufferInputStream(comments);
    DataInputStream dis = new DataInputStream(sbis);

    String str;
    while( ( str = dis.readLine() ) != null )
    {
      System.out.println(str);
    }
    dis.close();   sbis.close();
  }
}


StringBufferInputStream Example
Output screen on StringBufferInputStream Example

String comments = "Improve\nthe\ncontent\nwith\nyour\nvalueble\ncomments";

In the above string comments, the delimiter (separator) is \n.

StringBufferInputStream sbis = new StringBufferInputStream(comments);

The string comments is passed as parameter to StringBufferInputStream constructor. StringBufferInputStream is chained to DataInputStream (of course, following rules of chaining).

DataInputStream dis = new DataInputStream(sbis);

The readLine() method of DataInputStream reads each word delimited by \n in the string comments.

Leave a Comment

Your email address will not be published.