StringReader
类将普通字符串转换为reader
,而StringWriter
类则收集字符串缓冲区中的字符,该缓冲区用于构造字符串。 关闭StringReader
和StringWriter
无效。
以下是StringReader
类的示例。
文件:StringReaderExample.java –
package com.yiibai.tutorial.io; import java.io.IOException; import java.io.StringReader; /** * @author yiibai */ public class StringReaderExample { public static void main(String[] args) { String input = "This is an example of StringReader."; StringReader stringReader = new StringReader(input); int c; try { while ((c = stringReader.read()) != -1) { System.out.print((char) c); } } catch (IOException e) { e.printStackTrace(); } } }
输出结果:
This is an example of StringReader.
以下是StringWriter
类的示例。
文件:StringWriterExample.java –
package com.yiibai.tutorial.io; import java.io.StringWriter; /** * @author yiibai */ public class StringWriterExample { public static void main(String[] args) { StringWriter stringWriter = new StringWriter(); stringWriter.write("This is an example "); stringWriter.write("of StringWriter."); // Convert writer to String System.out.println(stringWriter.toString()); } }
输出结果:
This is an example of StringWriter.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264103.html