java inputstream转outputstream_如何将OutputStream转换为InputStream?

Nick Russler..

9

我遇到了将a转换ByteArrayOutputStream为a ByteArrayInputStream并通过使用派生类解决它的相同问题,派生类ByteArrayOutputStream能够返回ByteArrayInputStream使用内部缓冲区初始化的派生类ByteArrayOutputStream.这样就不会使用额外的内存而且'转换'非常快:

package info.whitebyte.utils;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

/**

* This class extends the ByteArrayOutputStream by

* providing a method that returns a new ByteArrayInputStream

* which uses the internal byte array buffer. This buffer

* is not copied, so no additional memory is used. After

* creating the ByteArrayInputStream the instance of the

* ByteArrayInOutStream can not be used anymore.

*

* The ByteArrayInputStream can be retrieved using getInputStream().

* @author Nick Russler

*/

public class ByteArrayInOutStream extends ByteArrayOutputStream {

/**

* Creates a new ByteArrayInOutStream. The buffer capacity is

* initially 32 bytes, though its size increases if necessary.

*/

public ByteArrayInOutStream() {

super();

}

/**

* Creates a new ByteArrayInOutStream, with a buffer capacity of

* the specified size, in bytes.

*

* @param size the initial size.

* @exception IllegalArgumentException if size is negative.

*/

public ByteArrayInOutStream(int size) {

super(size);

}

/**

* Creates a new ByteArrayInputStream that uses the internal byte array buffer

* of this ByteArrayInOutStream instance as its buffer array. The initial value

* of pos is set to zero and the initial value of count is the number of bytes

* that can be read from the byte array. The buffer array is not copied. This

* instance of ByteArrayInOutStream can not be used anymore after calling this

* method.

* @return the ByteArrayInputStream instance

*/

public ByteArrayInputStream getInputStream() {

// create new ByteArrayInputStream that respects the current count

ByteArrayInputStream in = new ByteArrayInputStream(this.buf, 0, this.count);

// set the buffer of the ByteArrayOutputStream

// to null so it can't be altered anymore

this.buf = null;

return in;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值