"안녕, 아미고!"

"안녕, 엘리!"

"오늘은 StringReaderStringWriter 클래스 에 대해 말씀드리고자 합니다 . 원칙적으로 새로운 내용은 많지 않을 것입니다. 하지만 이러한 클래스는 때때로 매우 유용합니다. 하지만 최소한 알아두셨으면 합니다. 그들이 존재한다는 것을."

"이 클래스는 추상적인 Reader 및 Writer 클래스의 가장 간단한 구현입니다. 기본적으로 FileReader 및 FileWriter와 유사합니다. 그러나 이와는 달리 디스크의 파일에 있는 데이터로 작동하지 않습니다. 대신 문자열로 작동합니다. JVM의 메모리에."

"왜 그런 수업이 필요할까요?"

"때때로 그것들이 필요합니다. 본질적으로 StringReader는 StringReader 클래스 사이의 어댑터입니다 . 그리고 StringWriter 는 Writer를 상속하는 문자열입니다 . 예... 그게 최선의 설명이 아니라는 것을 알 수 있습니다. 먼저 예를 들겠습니다."

"예를 들어 전달된 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의 메서드를 테스트해 보겠습니다. 이를 위해 예제를 더 복잡하게 만들 것입니다. 이제 단순히 줄을 읽고 화면에 표시하는 것이 아니라 대신 그것들을 뒤집고 라이터 객체로 출력할 것입니다. 예를 들면 다음과 같습니다."

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 개체를 만들었습니다 . 그리고 그것을 얻으려면 toString () 메서드를 호출하기만 하면 됩니다."

"음. 어쩐지 모든 것이 너무 쉬운 것 같습니다. 실행자 방법은 판독기 기록기 스트림 개체와 함께 작동하지만 우리는 기본 방법에서 문자열로 작업하고 있습니다.

"정말 그렇게 간단합니까?"

"예. String을 Reader 로 변환하려면 다음과 같이 작성하십시오."

문자열에서 판독기 만들기
String s = "data";
Reader reader = new StringReader(s);

"그리고 StringWriter를 String으로 변환하는 것이 훨씬 더 쉽습니다."

작성기에서 문자열 가져오기
Writer writer = new StringWriter();
/* Here we write a bunch of data to the writer */
String result = writer.toString();

"제 생각에는 이것들은 훌륭한 수업들입니다. 그들에 대해 말해줘서 고마워요, Ellie."