本章,我们学习CharArrayWriter。学习时,我们先对CharArrayWriter有个大致了解,然后深入了解一下它的源码,最后通过示例来掌握它的用法。

转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_19.html 

更多内容请参考:Java io系列 "目录" 

CharArrayWriter 介绍

CharArrayReader 用于写入数据符,它继承于Writer。操作的数据是以字符为单位!

CharArrayWriter 函数列表

  1. CharArrayWriter()
  2. CharArrayWriter(int initialSize)
  3.  
  4. CharArrayWriter append(CharSequence csq, int start, int end)
  5. CharArrayWriter append(char c)
  6. CharArrayWriter append(CharSequence csq)
  7. void close()
  8. void flush()
  9. void reset()
  10. int size()
  11. char[] toCharArray()
  12. String toString()
  13. void write(char[] buffer, int offset, int len)
  14. void write(int oneChar)
  15. void write(String str, int offset, int count)
  16. void writeTo(Writer out)

Writer和CharArrayWriter源码分析

Writer是CharArrayWriter的父类,我们先看看Writer的源码,然后再学CharArrayWriter的源码。

1. Writer源码分析(基于jdk1.7.40)

  1. package java.io;
  2.  
  3. public abstract class Writer implements Appendable, Closeable, Flushable {
  4.  
  5. private char[] writeBuffer;
  6.  
  7. private final int writeBufferSize = 1024;
  8.  
  9. protected Object lock;
  10.  
  11. protected Writer() {
  12. this.lock = this;
  13. }
  14.  
  15. protected Writer(Object lock) {
  16. if (lock == null) {
  17. throw new NullPointerException();
  18. }
  19. this.lock = lock;
  20. }
  21.  
  22. public void write(int c) throws IOException {
  23. synchronized (lock) {
  24. if (writeBuffer == null){
  25. writeBuffer = new char[writeBufferSize];
  26. }
  27. writeBuffer[0] = (char) c;
  28. write(writeBuffer, 0, 1);
  29. }
  30. }
  31.  
  32. public void write(char cbuf[]) throws IOException {
  33. write(cbuf, 0, cbuf.length);
  34. }
  35.  
  36. abstract public void write(char cbuf[], int off, int len) throws IOException;
  37.  
  38. public void write(String str) throws IOException {
  39. write(str, 0, str.length());
  40. }
  41.  
  42. public void write(String str, int off, int len) throws IOException {
  43. synchronized (lock) {
  44. char cbuf[];
  45. if (len <= writeBufferSize) {
  46. if (writeBuffer == null) {
  47. writeBuffer = new char[writeBufferSize];
  48. }
  49. cbuf = writeBuffer;
  50. } else { // Don't permanently allocate very large buffers.
  51. cbuf = new char[len];
  52. }
  53. str.getChars(off, (off + len), cbuf, 0);
  54. write(cbuf, 0, len);
  55. }
  56. }
  57.  
  58. public Writer append(CharSequence csq) throws IOException {
  59. if (csq == null)
  60. write("null");
  61. else
  62. write(csq.toString());
  63. return this;
  64. }
  65.  
  66. public Writer append(CharSequence csq, int start, int end) throws IOException {
  67. CharSequence cs = (csq == null ? "null" : csq);
  68. write(cs.subSequence(start, end).toString());
  69. return this;
  70. }
  71.  
  72. public Writer append(char c) throws IOException {
  73. write(c);
  74. return this;
  75. }
  76.  
  77. abstract public void flush() throws IOException;
  78.  
  79. abstract public void close() throws IOException;
  80. }

2. CharArrayWriter 源码分析(基于jdk1.7.40)

  1. package java.io;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class CharArrayWriter extends Writer {
  6. // 字符数组缓冲
  7. protected char buf[];
  8.  
  9. // 下一个字符的写入位置
  10. protected int count;
  11.  
  12. // 构造函数:默认缓冲区大小是32
  13. public CharArrayWriter() {
  14. this(32);
  15. }
  16.  
  17. // 构造函数:指定缓冲区大小是initialSize
  18. public CharArrayWriter(int initialSize) {
  19. if (initialSize < 0) {
  20. throw new IllegalArgumentException("Negative initial size: "
  21. + initialSize);
  22. }
  23. buf = new char[initialSize];
  24. }
  25.  
  26. // 写入一个字符c到CharArrayWriter中
  27. public void write(int c) {
  28. synchronized (lock) {
  29. int newcount = count + 1;
  30. if (newcount > buf.length) {
  31. buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
  32. }
  33. buf[count] = (char)c;
  34. count = newcount;
  35. }
  36. }
  37.  
  38. // 写入字符数组c到CharArrayWriter中。off是“字符数组b中的起始写入位置”,len是写入的长度
  39. public void write(char c[], int off, int len) {
  40. if ((off < 0) || (off > c.length) || (len < 0) ||
  41. ((off + len) > c.length) || ((off + len) < 0)) {
  42. throw new IndexOutOfBoundsException();
  43. } else if (len == 0) {
  44. return;
  45. }
  46. synchronized (lock) {
  47. int newcount = count + len;
  48. if (newcount > buf.length) {
  49. buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
  50. }
  51. System.arraycopy(c, off, buf, count, len);
  52. count = newcount;
  53. }
  54. }
  55.  
  56. // 写入字符串str到CharArrayWriter中。off是“字符串的起始写入位置”,len是写入的长度
  57. public void write(String str, int off, int len) {
  58. synchronized (lock) {
  59. int newcount = count + len;
  60. if (newcount > buf.length) {
  61. buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
  62. }
  63. str.getChars(off, off + len, buf, count);
  64. count = newcount;
  65. }
  66. }
  67.  
  68. // 将CharArrayWriter写入到“Writer对象out”中
  69. public void writeTo(Writer out) throws IOException {
  70. synchronized (lock) {
  71. out.write(buf, 0, count);
  72. }
  73. }
  74.  
  75. // 将csq写入到CharArrayWriter中
  76. // 注意:该函数返回CharArrayWriter对象
  77. public CharArrayWriter append(CharSequence csq) {
  78. String s = (csq == null ? "null" : csq.toString());
  79. write(s, 0, s.length());
  80. return this;
  81. }
  82.  
  83. // 将csq从start开始(包括)到end结束(不包括)的数据,写入到CharArrayWriter中。
  84. // 注意:该函数返回CharArrayWriter对象!
  85. public CharArrayWriter append(CharSequence csq, int start, int end) {
  86. String s = (csq == null ? "null" : csq).subSequence(start, end).toString();
  87. write(s, 0, s.length());
  88. return this;
  89. }
  90.  
  91. // 将字符c追加到CharArrayWriter中!
  92. // 注意:它与write(int c)的区别。append(char c)会返回CharArrayWriter对象。
  93. public CharArrayWriter append(char c) {
  94. write(c);
  95. return this;
  96. }
  97.  
  98. // 重置
  99. public void reset() {
  100. count = 0;
  101. }
  102.  
  103. // 将CharArrayWriter的全部数据对应的char[]返回
  104. public char toCharArray()[] {
  105. synchronized (lock) {
  106. return Arrays.copyOf(buf, count);
  107. }
  108. }
  109.  
  110. // 返回CharArrayWriter的大小
  111. public int size() {
  112. return count;
  113. }
  114.  
  115. public String toString() {
  116. synchronized (lock) {
  117. return new String(buf, 0, count);
  118. }
  119. }
  120.  
  121. public void flush() { }
  122.  
  123. public void close() { }
  124. }

说明
CharArrayWriter实际上是将数据写入到“字符数组”中去。
(01) 通过CharArrayWriter()创建的CharArrayWriter对应的字符数组大小是32。
(02) 通过CharArrayWriter(int size) 创建的CharArrayWriter对应的字符数组大小是size。
(03) write(int oneChar)的作用将int类型的oneChar换成char类型,然后写入到CharArrayWriter中。
(04) write(char[] buffer, int offset, int len) 是将字符数组buffer写入到输出流中,offset是从buffer中读取数据的起始偏移位置,len是读取的长度。
(05) write(String str, int offset, int count) 是将字符串str写入到输出流中,offset是从str中读取数据的起始位置,count是读取的长度。
(06) append(char c)的作用将char类型的c写入到CharArrayWriter中,然后返回CharArrayWriter对象。
注意:append(char c)与write(int c)都是将单个字符写入到CharArrayWriter中。它们的区别是,append(char c)会返回CharArrayWriter对象,但是write(int c)返回void。
(07) append(CharSequence csq, int start, int end)的作用将csq从start开始(包括)到end结束(不包括)的数据,写入到CharArrayWriter中。
注意:该函数返回CharArrayWriter对象!
(08) append(CharSequence csq)的作用将csq写入到CharArrayWriter中。
注意:该函数返回CharArrayWriter对象!
(09) writeTo(OutputStream out) 将该“字符数组输出流”的数据全部写入到“输出流out”中。

示例代码

关于CharArrayWriter中API的详细用法,参考示例代码(CharArrayWriterTest.java):

  1. import java.io.CharArrayReader;
  2. import java.io.CharArrayWriter;
  3. import java.io.IOException;
  4.  
  5. /**
  6. * CharArrayWriter 测试程序
  7. *
  8. * @author skywang
  9. */
  10. public class CharArrayWriterTest {
  11.  
  12. private static final int LEN = 5;
  13. // 对应英文字母“abcdefghijklmnopqrstuvwxyz”
  14. private static final char[] ArrayLetters = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  15.  
  16. public static void main(String[] args) {
  17.  
  18. tesCharArrayWriter() ;
  19. }
  20.  
  21. /**
  22. * CharArrayWriter的API测试函数
  23. */
  24. private static void tesCharArrayWriter() {
  25. try {
  26. // 创建CharArrayWriter字符流
  27. CharArrayWriter caw = new CharArrayWriter();
  28.  
  29. // 写入“A”个字符
  30. caw.write('A');
  31. // 写入字符串“BC”个字符
  32. caw.write("BC");
  33. //System.out.printf("caw=%s\n", caw);
  34. // 将ArrayLetters数组中从“3”开始的后5个字符(defgh)写入到caw中。
  35. caw.write(ArrayLetters, 3, 5);
  36. //System.out.printf("caw=%s\n", caw);
  37.  
  38. // (01) 写入字符0
  39. // (02) 然后接着写入“123456789”
  40. // (03) 再接着写入ArrayLetters中第8-12个字符(ijkl)
  41. caw.append('0').append("123456789").append(String.valueOf(ArrayLetters), 8, 12);
  42.  
  43. System.out.printf("caw=%s\n", caw);
  44.  
  45. // 计算长度
  46. int size = caw.size();
  47. System.out.printf("size=%s\n", size);
  48.  
  49. // 转换成byte[]数组
  50. char[] buf = caw.toCharArray();
  51. System.out.printf("buf=%s\n", String.valueOf(buf));
  52.  
  53. // 将caw写入到另一个输出流中
  54. CharArrayWriter caw2 = new CharArrayWriter();
  55. caw.writeTo(caw2);
  56. System.out.printf("caw2=%s\n", caw2);
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }

运行结果

caw=ABCdefgh0123456789ijkl
size=22
buf=ABCdefgh0123456789ijkl
caw2=ABCdefgh0123456789ijkl

java io系列19之 CharArrayWriter(字符数组输出流)的更多相关文章

  1. java io系列24之 BufferedWriter(字符缓冲输出流)

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_24.html 更多内容请参考:java io系列01之 "目录" Buffere ...

  2. java io系列25之 PrintWriter (字符打印输出流)

    更多内容请参考:java io系列01之 "目录" PrintWriter 介绍 PrintWriter 是字符类型的打印输出流,它继承于Writer.PrintStream 用于 ...

  3. java io系列18之 CharArrayReader(字符数组输入流)

    从本章开始,我们开始对java io中的“字符流”进行学习.首先,要学习的是CharArrayReader.学习时,我们先对CharArrayReader有个大致了解,然后深入了解一下它的源码,最后通 ...

  4. java io系列23之 BufferedReader(字符缓冲输入流)

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_23.html 更多内容请参考:java io系列01之 "目录" Buffere ...

  5. Java IO学习--(五)字节和字符数组

    内容列表 从InputStream或者Reader中读入数组 从OutputStream或者Writer中写数组 在java中常用字节和字符数组在应用中临时存储数据.而这些数组又是通常的数据读取来源或 ...

  6. java io系列01之 "目录"

    java io 系列目录如下: 01. java io系列01之  "目录" 02. java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括 ...

  7. java io系列

    java io系列01之 "目录" java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream) java io系列03之 ...

  8. java io系列16之 PrintStream(打印输出流)详解

    本章介绍PrintStream以及 它与DataOutputStream的区别.我们先对PrintStream有个大致认识,然后再深入学习它的源码,最后通过示例加深对它的了解. 转载请注明出处:htt ...

  9. java io系列15之 DataOutputStream(数据输出流)的认知、源码和示例

    本章介绍DataOutputStream.我们先对DataOutputStream有个大致认识,然后再深入学习它的源码,最后通过示例加深对它的了解. 转载请注明出处:http://www.cnblog ...

随机推荐

  1. jquery 循环绑定click的问题

    之前循环数据,通过live绑定click, 发觉每个click绑定的链接参数都是一样的. 后来改用 直接的 click绑定,就好了. $.each(ship.PPRList, function (i, ...

  2. Python中xlrd模块解析

    xlrd 导入模块 import xlrd 2.打开指定的excel文件,返回一个data对象 data = xlrd.open_workbook(file)                     ...

  3. Python中操作ini配置文件

    这篇博客我主要想总结一下python中的ini文件的使用,最近在写python操作mysql数据库,那么作为测试人员测试的环境包括(测试环境,UAT环境,生产环境)每次需要连接数据库的ip,端口,都会 ...

  4. JOI 2018 Final 题解

    题目列表:https://loj.ac/problems/search?keyword=JOI+2018+Final T1 寒冬暖炉 贪心 暴力考虑每相邻两个人之间的间隔,从小到大选取即可 #incl ...

  5. CCF WC2017 & THU WC2017 旅游记

    day-x 真·旅游 去了杭州的一些景点,打了几场练习赛. day0 报到日 领资料.入住,中午在食堂吃饭,感觉做的挺好的,和二高食堂差不多.晚上还有开幕式. day1~day4 白天讲课,晚上营员交 ...

  6. PSR-0 规范实例讲解 -- php 自动加载

    PSR-0规范 [1]命名空间必须与绝对路径一致 [2]类名首字母必须大写 [3]除去入口文件外,其他“.php”必须只有一个类 [4]php类文件必须自动载入,不采用include等 [5]单一入口 ...

  7. Hdoj 1058.Humble Numbers 题解

    Problem Description A number whose only prime factors are 2,3,5 or 7 is called a humble number. The ...

  8. 文艺平衡树 Splay 学习笔记(1)

    (这里是Splay基础操作,reserve什么的会在下一篇里面讲) 好久之前就说要学Splay了,结果苟到现在才学习. 可能是最近良心发现自己实在太弱了,听数学又听不懂只好多学点不要脑子的数据结构. ...

  9. 简单使用TFS管理源代码

    今天研究使用了一下TFS,主要是想管理源代码.不涉汲团队管理. 使用环境W10专业版  / VS2017 社区版 / SQLSERVER2016  / TFS2017 EXPRESS版本 1.下载和安 ...

  10. 【转】WEB服务器与应用服务器的区别

    https://blog.csdn.net/liupeng900605/article/details/7661406 一.简述 WEB服务器与应用服务器的区别: 1.WEB服务器: 理解WEB服务器 ...