Java CharArrayReader和CharArrayWriter类示例

CharArrayReader类和CharArrayWriter类实现了一个字符缓冲区,可以分别用作字符输入流和字符输出流。 调用CharArrayReader类和CharArrayWriter类的close()方法无效。

以下是CharArrayReader类的示例。文件:CharArrayReaderExample.java

package com.yiibai.tutorial.io;  import java.io.CharArrayReader; import java.io.IOException;  /**  * @author yiibai  */ public class CharArrayReaderExample {     public static void main(String[] args) {         char ch[] = "This is an example of CharArrayReader.".toCharArray();         CharArrayReader charArrayReader = null;         try {             charArrayReader = new CharArrayReader(ch);              // Read characters             int c;             while ((c = charArrayReader.read()) != -1) {                 System.out.print((char) c);             }         } catch (IOException e) {             e.printStackTrace();         }     } } 

执行上面示例代码,得到以下结果:

This is an example of CharArrayReader. 

以下是CharArrayWriter类的示例。

文件:CharArrayWriterExample.java

package com.yiibai.tutorial.io;  import java.io.CharArrayWriter; import java.io.IOException;  /**  * @author yiibai  */ public class CharArrayWriterExample {     public static void main(String[] args) {         CharArrayWriter charArrayWriter = new CharArrayWriter();          try {             // Write characters to Writer             charArrayWriter.write("This is an example of CharArrayWriter");              // Get character array from writer             char[] ch = charArrayWriter.toCharArray();             for (char c : ch) {                 System.out.print(c);             }         } catch (IOException e) {             e.printStackTrace();         }      } } 

执行上面示例代码,得到以下结果:

This is an example of CharArrayWriter 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264102.html

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

相关推荐

发表回复

登录后才能评论