IO_字节数组流

IO_字节数组流操作步骤
读操作
1.创建源,使用byte[]字节数组类,如果是字符串可以用getByte()方法获得其字节;
2.选择流,使用InputStream类,创建一个ByteArrayInputStream(src)类的流
3.操作写内容,先创建一个缓存数组空间,再进行写操作
4.不需要释放

import java.io.*;

public class IOCopy {
	public static void main(String[] agrs) {
		//1.create
		byte[] src="talk is cheap show me your code".getBytes();
		//2.choose
		InputStream is=null;
		is=new ByteArrayInputStream(src);
		//3.operate
		byte[] flush=new byte[5];
		int len =-1;
		try {
			while((len=is.read(flush))!=-1) {
				String str=new String(flush,0,len);
				System.out.print(str);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

输出结果

talk is cheap show me your code

PS:缓存区flush的大小变化影响的是每次读取的字节数

写操作
1.创建源,源设为空,因为不好定义数组大小,干脆不定义,内部维护,不建也可以
2.选择字节数组输出流,ByteArrayOutputStream类,因为这个方法是新增方法,并且该类无有参构造器所以需要注意,不能用父类去声明,不关联源,即不写入源;
3.操作写
4.不用释放

package cn.xl.IO;

import java.io.*;

public class IOCopy {
	public static void main(String[] agrs) {
		//1.创建源
		byte[] dest=null;
		//2.选择流(新增方法)
		ByteArrayOutputStream baos=null;
		baos=new ByteArrayOutputStream();
		//3.操作
		String msg="show me your code";
		byte[] datas=msg.getBytes();
		baos.write(datas,0,datas.length);
		try {
			baos.flush();//刷新
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//4.获取数据
		dest=baos.toByteArray();
		System.out.println(new String(dest,0,dest.length));
		
	}
}

猜你喜欢

转载自blog.csdn.net/layAlex/article/details/104582020