“嗨,阿米戈!”

“嗨,艾莉!”

“今天我想给大家介绍一下StringReaderStringWriter类。原则上对你来说不会有太多新的东西,但有时这些类非常有用。但是,至少,我想让你知道他们存在。”

“这些类是抽象 Reader 和 Writer 类的最简单实现。它们基本上类似于 FileReader 和 FileWriter。但是,与它们不同的是,它们不处理磁盘上文件中的数据。相反,它们处理 String在 JVM 的内存中。”

“为什么我们需要这样的课程?”

“有时需要它们。本质上,StringReader是StringReader类之间的适配器。而StringWriter是继承Writer的 String 。是的......我可以说这不是最好的解释。最好看一对首先是例子。”

“例如,假设您想测试您的方法,该方法从传递给它的 Reader 对象中读取数据。我们可以这样做:”

从 Reader 对象读取:
public static void main (String[] args) throws Exception
{
 String test = "Hi!\n My name is Richard\n I'm a photographer\n";

 // This line is key: we "convert" the String into a Reader.
 StringReader reader = new StringReader(test);

 executor(reader);
}

public static void executor(Reader reader) throws Exception
{
 BufferedReader br = new BufferedReader(reader);
 String line;
 while (line = br.readLine() != null)
 {
 System.out.println(line);
 }
}

“换句话说,我们只是简单地获取了一个字符串,将它包装在一个 StringReader 中,然后传递它而不是一个 Reader 对象?所有的东西都会像我们需要的那样从中读取?”

“是的。嗯。这有一点。现在让我们测试 StringWriter 的方法。为此,我们将使示例更复杂。现在它不会简单地读取行并将它们显示在屏幕上,而是它将反转它们并将它们输出到 writer 对象。例如:“

从 reader 对象读取并写入 writer 对象:
public static void main (String[] args) throws Exception
{
 // The Reader must read this String.
 String test = "Hi!\n My name is Richard\n I'm a photographer\n";

 // Wrap the String in a StringReader.
 StringReader reader = new StringReader(test);

 // Create a StringWriter object.
 StringWriter writer = new StringWriter();

 // Copy strings from the Reader to the Writer, after first reversing them.
 executor(reader, writer);

 // Get the text that was written to the Writer.
 String result = writer.toString();

 // Display the text from the Writer on the screen.
 System.out.println("Result: "+ result);
}

public static void executor(Reader reader, Writer writer) throws Exception
{
 BufferedReader br = new BufferedReader(reader);
String line;

 // Read a string from the Reader.
while (line = br.readLine()) != null)
 {

 // Reverse the string.
  StringBuilder sb = new StringBuilder(line);
  String newLine = sb.reverse().toString();

 // Write the string to the Writer.
  writer.write(newLine);
 }
}

“我们创建了一个StringWriter对象,其中包含一个字符串,该字符串存储写入此writer 的所有内容。要获取它,您只需调用toString () 方法。”

“嗯。不知怎的,这一切似乎太简单了。执行器方法与读取器写入器流对象一起使用,但我们在 main 方法中使用字符串。

“真的那么简单吗?”

“是的。要将 String 转换为Reader,只需这样写:”

从字符串创建阅读器
String s = "data";
Reader reader = new StringReader(s);

“将 StringWriter 转换为 String 甚至更容易:”

从 Writer 获取字符串
Writer writer = new StringWriter();
/* Here we write a bunch of data to the writer */
String result = writer.toString();

“在我看来,这些都是很棒的课程。谢谢你告诉我这些,艾莉。”