zoukankan      html  css  js  c++  java
  • IO_ByteArrayInputStream&ByteArrayOutputStream

    ByteArrayInputStream中包含一个内部缓冲区,用来包含那些可能从流中读的字节数组。还有一个内部计数器来跟踪下一个将被读取的字节。
    ByteArrayInputStream传入一个字节数组进行构造。
    流的来源或目的地并不一定是文件,也可以是内存中的一块空间。ByteArrayInputStream、ByteArrayOutputStream就是将字节数组当作流输入来源、输出目的地的类
    有时需要对InputStream对象使用多次。比如:既想把数据显示到前台。又想写进文件缓存到本次,而InputStream不可复制,就可以将InputStream转换成ByteArrayOutputStream。后要想使用InputStream,把ByteArrayOutputStream转换回来就可以。

    //创建一个InputStream流
    InputStream input =  httpconn.getInputStream();
    
    //读InputStream流中的数据并写到数组内存中             
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int len;
    while ((len = input.read(b)) > -1 ) {
        baos.write(buffer, 0, len);
    }
                 
    //流中的数据使用方式一:
    InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
    //流中的数据使用方式二:
    InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());
    
    

    public class ByteArrayInpuStreamJava {
    
    	public static void main(String[] args) throws IOException {
    		// TODO Auto-generated method stub
    		String strFile = "d:" + File.separator + "javatest" + File.separator + "IO_RandomAccessFileTest.txt";
    		File f = new File(strFile);
    		FileInputStream fis = new FileInputStream(f);
    		byte[] fisByte = new byte[1024];
    		while ((fis.read(fisByte)) != -1) {
    			//将读进来的数据写到内存
    			ByteArrayInputStream bais = new ByteArrayInputStream(fisByte);
    			
    			ByteArrayOutputStream baos = new ByteArrayOutputStream();
    			//读内存中的数据
    			baos.write(fisByte, 0, fisByte.length);
    			byte[] b = baos.toByteArray();
    			System.out.println(new String(b));
    		}
    
    		fis.close();
    	}
    
    }
    
  • 相关阅读:
    Average of Levels in Binary Tree
    Maximum Average Subarray I
    Integer Replacement
    Add Digits
    Binary Tree Level Order Traversal II
    Majority Element II
    Majority Element
    匿名函数
    Django的Template不支持range()函数的问题解决办法
    python文件对比利用difflib库实现文件夹下详细内容对比
  • 原文地址:https://www.cnblogs.com/changzuidaerguai/p/9277285.html
Copyright © 2011-2022 走看看