Java中的 StringWriter getBuffer() 方法及示例
Java中StringWriter类的getBuffer()方法用于获取这个StringWriter实例的StringBuffer表示。此方法不接受任何参数并返回所需的 StringBuffer 值。
句法:
public StringBuffer getBuffer()
参数:此方法接受不接受任何参数。
返回值:此方法返回一个 StringBuffer 值,它是 StringWriter 实例的 StringBuffer 表示形式。
下面的方法说明了 getBuffer() 方法的工作:
方案一:
// Java program to demonstrate
// StringWriter getBuffer() method
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
// Create a StringWriter instance
StringWriter writer
= new StringWriter();
// Get the String
// to be written in the stream
String string = "GeeksForGeeks";
// Write the the string
// to this writer using write() method
writer.write(string);
// Get the StringBuffer of this StringWriter
StringBuffer stringBuffer = writer.getBuffer();
System.out.println("StringBuffer representation: "
+ stringBuffer);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
StringBuffer representation: GeeksForGeeks
方案二:
// Java program to demonstrate
// StringWriter getBuffer() method
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
// Create a StringWriter instance
StringWriter writer
= new StringWriter();
// Get the String
// to be written in the stream
String string = "GFG";
// Write the the string
// to this writer using write() method
writer.write(string);
// Get the StringBuffer of this StringWriter
StringBuffer stringBuffer = writer.getBuffer();
System.out.println("StringBuffer representation: "
+ stringBuffer);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
StringBuffer representation: GFG