Java IO: ByteArrayOutputStream使用

感谢原文作者:小思思smile
原文链接:https://blog.csdn.net/u014049880/article/details/52329333/
更多请查阅Java API文档!

在创建ByteArrayOutputStream类实例时,内存中会创建一个byte数组类型的缓冲区,缓冲区会随着数据的不断写入而自动增长

可使用toByteArray()toString()获取数据。

关闭ByteArrayOutputStream无效,此类中的方法在关闭此流后仍可被调用,而不会产生任何IOException
在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去

示例

示例一:

public static void main(String[] args) { 
    int a = 0; 
    int b = 1; 
    int c = 2; 
    ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
    bout.write(a); 
    bout.write(b); 
    bout.write(c); 
    byte[] buff = bout.toByteArray(); 
    for (int i = 0; i < buff.length; i++) 
        System.out.println(buff[i]); 
    System.out.println("***********************"); 
    ByteArrayInputStream bin = new ByteArrayInputStream(buff); 
    while ((b = bin.read()) != -1) { 
        System.out.println(b); 
    } 
}

示例二:

	/**
	 * 读取文件内容
	 * 
	 * @param filename 文件名
	 * @return
	 */
	public String read(String filename) throws Exception
	{
		FileInputStream fis = new.FileInputStream(filename); 
		ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
		byte[] buffer = new byte[1024];
		int len = 0;
		// 将内容读到buffer中,读到末尾为-1
		while ((len = fis.read(buffer)) != -1)
		{
			// 本例子将每次读到字节数组(buffer变量)内容写到内存缓冲区中,起到保存每次内容的作用
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray(); // 取内存中保存的数据
		fis.close();
		String result = new String(data, "UTF-8");
		return result;
	}

我的项目实际使用

仓库地址:https://github.com/b84955189/TF-MIS
源路径:src/main/java/utils/CommonUtils.java


    /**
     * 将输入流转为字节数组
     * @author Jason
     * @date 9:49 AM 6/19/2020
     * @param
     * @return
     */
    public static byte[] toByteArray(InputStream in) throws IOException {
        ByteOutputStream byteOutputStream = new ByteOutputStream();
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len=in.read(bytes))!=-1){
             byteOutputStream.write(bytes,0,len);
        }
        return  byteOutputStream.toByteArray();
    }
posted @ 2020-07-05 19:39  超级小白龙  阅读(2389)  评论(0编辑  收藏  举报