StringWriter 在 Java 中的重要性是什么?
StringWriter 类是 Writer 类的子类,它将字符串写入输出流。为了写入字符串,这个字符流将字符串收集到一个字符串缓冲区,然后构造一个字符串。StringWriter 的缓冲区会根据数据自动增加。StringWriter 类的重要方法包括 write()、append()、getBuffer()、flush() 和 close()。
语法
public class StringWriter extends Writer
示例
import java.io.*; public class StringWriterTest { public static void main(String args[]) { String str = "Welcome to Tutorials Point"; try { StringWriter sw = new StringWriter(); sw.write(str); StringBuffer sb = new StringBuffer(); sb = sw.getBuffer(); System.out.println("StringBuffer: "+ sb); System.out.println("String written by StringWriter: "+ sw); sw.close(); } catch (IOException ioe) { System.out.println(ioe); } } }
输出
StringBuffer: Welcome to Tutorials Point String written by StringWriter: Welcome to Tutorials Point
广告