Java中io流的学习(十)ByteArrayInoutStream和ByteArrayOutputStream

ByteArrayInputStream(内存输入流)继承于InputStream,ByteArrayOutputStream(内存输出流)继承于OutputStream。内存流是关不掉的,一般用来存放一些临时性的数据,理论值是内存大小。

常用的方法是:read(),一系列read方法,参照API,只是读取方式不同,一个一个字节读取,或者多个字节多个字节读取;write(),一系列write方法,参照API理解;toByteArray(),创建一个新分配的byte数组;toString(String charsetName),使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串。

下面通过实例代码来对其进行学习:

①从内存流读出信息,创建内存流时,就把数据存入到内存中

	@Test
	public void t1() throws Exception{
		ByteArrayInputStream bais = new ByteArrayInputStream("我是内存流测试".getBytes());
		byte[] b = new byte[1024];
		int len;
		while((len = bais.read(b)) != -1){
			System.out.println(new String(b, 0, len));
		}
	}

②将数据写入内存流

	@Test
	public void t2() throws Exception{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos.write("我是内存流测试".getBytes());
		//输出方式一
		byte[] b = baos.toByteArray();
		System.out.println(new String(b));
		//输出方式二
		String s = baos.toString();
		System.out.println(s);
	}

 

Java中io流的学习(一)File:https://blog.csdn.net/qq_41061437/article/details/81672859

Java中io流的学习(二)FileInputStream和FileOutputStream:https://blog.csdn.net/qq_41061437/article/details/81742175

Java中io流的学习(三)BuffereInputStream和BuffereOutputStream:https://blog.csdn.net/qq_41061437/article/details/81743522

Java中io流的学习(四)InputStreamReader和OutputStreamWriter:https://blog.csdn.net/qq_41061437/article/details/81745300

Java中io流的学习(五)FileReader和FileWriter:https://blog.csdn.net/qq_41061437/article/details/81747105

 

Java中io流的学习(六)BufferedReader和BufferedWriter:https://blog.csdn.net/qq_41061437/article/details/81747323

Java中io流的学习(七)ObjectInputStream和ObjectOutputStream:https://blog.csdn.net/qq_41061437/article/details/81748461

Java中io流的学习(八)PrintStream和PrintWriter:https://blog.csdn.net/qq_41061437/article/details/81782770

Java中io流的学习(九)RandomAccessFile:https://blog.csdn.net/qq_41061437/article/details/81805351

Java中io流的学习(十)ByteArrayInoutStream和ByteArrayOutputStream:https://blog.csdn.net/qq_41061437/article/details/81806245

Java中io流的学习(十一)NIO:https://blog.csdn.net/qq_41061437/article/details/81809370

Java中io流的学习(总结):https://blog.csdn.net/qq_41061437/article/details/81740680

你可能感兴趣的:(Java学习)