IO流-字节数组流-Java

ByteArrayInputStream和ByteArrayOutputStream经常用在需要流和数组之间转换的情况。

字节数组输入流

FileInputStream是把文件当作数据源。ByteArrayInputStream是把内存中的"字节数组对象"当做数据源。

import java.io.*;
public class ByteArrayInputDemo {
	public static void main(String[] args) {
		byte[] arr = "abcd".getBytes();
		ByteArrayInputStream bis = null;
		StringBuilder sb = new StringBuilder();
		try {
			//该构造方法的参数是一个字节数组,这个字节数组就是数据源
			bis = new ByteArrayInputStream(arr);
			int temp = 0;
			while((temp = bis.read())!=-1) {
				sb.append((char)temp);
			}
			System.out.println(sb.toString());
		}finally {
			try {
				bis.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}

字节数组输出流

ByteArrayOutputStream流对象是将流中的数据写入到字节数组中。

import java.io.*;
public class ByteArrayOutputDemo {
	public static void main(String[] args) {
		ByteArrayOutputStream bos = null;
		try {
			StringBuilder sb = new StringBuilder();
			bos = new ByteArrayOutputStream();
			bos.write('a');
			bos.write('b');
			bos.write('c');
			byte[] arr = bos.toByteArray();
			for(int i=0;i<arr.length;i++) {
				System.out.println(arr[i]);
				sb.append((char)arr[i]);
			}
			System.out.println(sb.toString());
		}finally {
			try {
				if(bos!=null) {
					bos.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}


版权声明:本文为lipengfei0427原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。