“嗨,阿米戈!”
“嗨,艾莉!”
“今天我想給大家介紹一下StringReader和StringWriter類。原則上對你來說不會有太多新的東西,但有時這些類非常有用。但是,至少,我想讓你知道他們存在。”
“這些類是抽象 Reader 和 Writer 類的最簡單實現。它們基本上類似於 FileReader 和 FileWriter。但是,與它們不同的是,它們不處理磁盤上文件中的數據。相反,它們處理 String在 JVM 的內存中。”
“為什麼我們需要這樣的課程?”
“有時需要它們。本質上,StringReader是String和Reader類之間的適配器。而StringWriter是繼承Writer的 String 。是的......我可以說這不是最好的解釋。最好看一對首先是例子。”
“例如,假設您想測試您的方法,該方法從傳遞給它的 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 對象。例如:“
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 = new StringWriter();
/* Here we write a bunch of data to the writer */
String result = writer.toString();
“在我看來,這些都是很棒的課程。謝謝你告訴我這些,艾莉。”
GO TO FULL VERSION