Java StringReader和StringWriter示例

StringReader类将普通字符串转换为reader,而StringWriter类则收集字符串缓冲区中的字符,该缓冲区用于构造字符串。 关闭StringReaderStringWriter无效。

以下是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

(0)
上一篇 2022年6月7日
下一篇 2022年6月7日

相关推荐

发表回复

登录后才能评论