Java---IO流内存流

3/8/2017来源:ASP.NET技巧人气:1299

这里写图片描述

package cn.hncu.io.array; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.CharArrayReader; import java.io.CharArrayWriter; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; /* * ★字节数组流 ByteArrayInputStream与ByteArrayOutputStream ★字符数组流 CharArrayReader与CharArrayWriter ★字符串流 StringReader 与 StringWriter 1、用于操作字节数组的流对象,其实它们就是对应设备为内存的流对象。 2、该流的关闭是无效的,因为没有调用过系统资源。 3、按照流的读写思想操作数组中元素。 */ public class XxxArrayXxputStream { public static void main(String[] args) { //byteArrayXxxStream(); //charArrayXxx(); stringXxx(); } PRivate static void stringXxx() { StringReader sr = new StringReader("我是字符串流的演示..."); StringWriter sw = new StringWriter(); int ch = 0; try { while((ch=sr.read())!=-1){ sw.write(ch);//每次读取一个字符写到输出流当中去 } System.out.println(sw.toString()); } catch (IOException e) { e.printStackTrace(); } } private static void charArrayXxx() { String strLine = "字符内存流的演示he he da!"; char[] buf = strLine.toCharArray(); CharArrayReader car = new CharArrayReader(buf); CharArrayWriter caw = new CharArrayWriter(); int ch = 0; try { while((ch=car.read())!=-1){//每次从buf数组中去读数据,读到-1时代表数据已经被读完 caw.write(ch); } System.out.println(caw.toString()); } catch (IOException e) { e.printStackTrace(); }finally{ car.close(); caw.close(); } } private static void byteArrayXxxStream() { //操纵对象--给的字符串 String strLine = "我是用来演示的字符串ni hao a!"; byte[] buf = strLine.getBytes();//拿到字节数组 ByteArrayInputStream bin = new ByteArrayInputStream(buf); ByteArrayOutputStream bout = new ByteArrayOutputStream(); int ch = 0; while((ch=bin.read())!=-1){ bout.write(ch);//将读取的内存流中的内容全部写到输出的内存流当中去 } System.out.println(bout.toString());//输出 } }