IO流之字节数组流和字符串流

 1.字节数组流

      字 节数组输出流ByteArrayOutputStream实现了一个输出流,其中的数据被写入一个byte数组,缓冲区会随着数据的不断写入而自动增长。 关闭ByteArrayOutputStream流无效,此类中的方法在关闭该流后还可以使用,而不会产生任何IOException,数据存放在内存。

      字节数组输出流ByteArrayInputStream实现了一个输入流,ByteArrayInputStream包含一个缓冲区,该缓冲区包含从流 中读取的字节,内部计数器跟踪read方法要读取的下一个字节。关闭ByteArrayInputStream流后,此类的方法也可以继续使用。因为数据 是在内存中。

示例代码:

public static void main(String[] args) {

		// 创建一个字节数组输出流对象
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		String data = "好好学习,天天向上";

		try {
			//写入字符串
			out.write(data.getBytes());
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//------------------------
		//根据字节数组构建字节数组输入流---out关闭后还可以调用toByteArray()方法
		ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray());
		byte[]bytes=new byte[512];
		int len=-1;
		StringBuilder sb=new StringBuilder();
		try {
			while((len=in.read(bytes))!=-1)
			{
				sb.append(new String(bytes,0,len));
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		
		System.out.println("data: "+sb);
	}

 运行结果:



 

2.字符串流

    字符串流的数据存放在内存中,关闭流后方法还可以继续调用,而不会产生任何IOException。StringWriter是字符串输入流,可以用其回收再字符串缓冲区的输出来构造字符串。

代码示例:

public static void main(String[] args) {

		//写入操作
		StringWriter sw=new StringWriter();
		
		try {
			sw.write("好好学习,天天向上");
			sw.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		//读取操作,根据一个字符串构造一个字符串输入流
		StringReader sr=new StringReader(sw.toString());
		
		char[]chars=new char[10];
		int len=-1;
		StringBuilder sb=new StringBuilder();
		try {
			while((len=sr.read(chars))!=-1)
			{
				sb.append(new String(chars,0,len));
			}
			sr.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println("data: "+sb);
	}

运行结果:



 

猜你喜欢

转载自longpo.iteye.com/blog/2203734