public class CharStreamDemo { /* 1、Writer extends Object implements Appendable,Closeable,Flushable close(); 关闭流 write(String str); 将字符串输出 write(char[] c); 将字符数组输出 flush(); 强制清空缓存 2、Reader extends Object implements Readable,Closeable; close(); 关闭输出流 read(); 读取单个字符 read(char[] c); 将内容读到字符数组,返回读到的长度 */ public static void main(String[] args) throws Exception{ // rotatingStream(); // executeCharFile(); // bufferStream(); } /**缓存流*/ public static void bufferStream() throws Exception{ try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(CharStreamUtis.readFile),"gbk")); BufferedWriter writer = new BufferedWriter(new FileWriter(CharStreamUtis.writeFile))){ String res = null; while ((res=reader.readLine()) != null) { // String print = new String(res.getBytes("UTF-8")); writer.write(res); } writer.flush(); } System.out.println("执行完毕"); } /**fileReader、fileWriter 操作文件,里边包装了转换流OutputStreamWriter、inputStreamReader,是对转换流的一个包装,运用此流要注意乱码问题*/ public static void executeCharFile() throws Exception{ try(FileReader reader = new FileReader(CharStreamUtis.readFile); FileWriter writer = new FileWriter(CharStreamUtis.writeFile)){ char[] cha = new char[1024]; int size = reader.read(cha); String str = null; while(size != -1){ str = new String(cha,0,size); writer.write(str); size = reader.read(cha); } } System.out.println("执行完毕"); } /** 转换流,字节转字符 ,其实最终还是以字节的方式进行输入输出的 * @throws Exception */ public static void rotatingStream() throws Exception{ InputStreamReader reader = new InputStreamReader(CharStreamUtis.getByteStream()); ByteArrayOutputStream byteOutStream = CharStreamUtis.getByteOutStream(); OutputStreamWriter writer = new OutputStreamWriter(byteOutStream); char[] ch = new char[1024]; int read = reader.read(ch); while (read != -1) { writer.write(ch,0,read); read = reader.read(ch); } CharStreamUtis.close(writer); CharStreamUtis.close(reader); System.out.println(byteOutStream.toString()); } } class CharStreamUtis{ public static final File readFile = new File("D:"+File.separator+"intest.txt"); public static final File writeFile = new File("D:"+File.separator+"outtest.txt"); /**将字节从内存流中读出*/ public static ByteArrayInputStream getByteStream(){ String str = "我爱中华!"; ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes()); return in; } /**将字节写入内存流*/ public static ByteArrayOutputStream getByteOutStream(){ ByteArrayOutputStream out = new ByteArrayOutputStream(); return out; } public static void close(Closeable closeable){ if(closeable != null){ try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void flush(Flushable flushable){ if(flushable != null){ try { flushable.flush(); } catch (IOException e) { e.printStackTrace(); } } } }
时间: 2024-11-06 03:52:40