Lesson 9 | String readers and writers |
Objective | Write a program that reads a file and stores its contents in a single string. |
String Readers Writers(Read File)
It's sometimes convenient to use a string as a source of data or a target for output. Since Java strings are made of Unicode characters, this requires readers and writers. The java.io.StringReader
class is initialized with a string and then reads successive characters from the string. The java.io.StringWriter
class writes output into a string, a character at a time, expanding the output string as necessary. Unlike most other readers and writers, the StringReader
and StringWriter
classes do not perform character set conversions. Since these classes operate completely inside Java, all reading and writing takes place in Unicode.
StringReader Class
The StringReader
class has the usual methods of Reader
classes plus one constructor. StringReaders
do support marking and resetting.
public StringReader(String s)
The StringWriter
class
The StringWriter
class has the usual methods of Writer
classes plus one public constructor:
public StringWriter()
You can use the toString()
method to return the String
that's been written with this writer. Alternatively, the getBuffer()
method returns the internal java.lang.StringBuffer
object used by this StringWriter
.
public String toString()
public StringBuffer getBuffer()
String Readers Writers - Exercise