IO:StringReader & StringWriter(字符串输入输出流)
程序员文章站
2022-04-30 18:21:59
...
※ 目的地
操作的目的地是字符串
※ StringReader 读取字符串的流
package com.briup.IO;
import java.io.IOException;
import java.io.StringReader;
import java.nio.CharBuffer;
import java.util.Arrays;
public class StringReaderTest {
public static void main(String[] args) {
StringReader sr=new StringReader("中hte号st");
int len=0;
/*char[] c=new char[10];
try {
while((len=sr.read(c))!=-1){
System.out.println(Arrays.toString(c));
}*/
//CharBuffer内部维护了一个缓存对象
CharBuffer cb=CharBuffer.allocate(10);
cb.append("test").append("go");
try {
//每read都是往缓存CharBuffer缓存中存储
while((len=sr.read(cb))!=-1){
//把往CharBuffer中放的数据刷入
cb.flip();
//取出CharBuffer内部缓存中的内容
System.out.println(cb.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
※ StringWriter 将字符写入StringWriter维护的缓存中
package com.briup.IO;
import java.io.IOException;
import java.io.StringWriter;
public class StringWriterTest {
public static void main(String[] args) {
//内部维护缓存(string对象)
StringWriter sw=new StringWriter();
sw.append("go");
sw.write("test");
sw.write('中');
try {
sw.write("hello".toCharArray());
sw.flush();
//获取缓存中的内容
System.out.println(sw.toString());
//获取缓存中的内容,内容装在StringBuffer对像中缓存
StringBuffer sb=sw.getBuffer();
//获取StringBuffer中缓存中的内容
System.out.println(sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}