001/* 002 * Copyright 2013 Chris Pheby 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.jadira.lang.io.buffered; 017 018import java.io.OutputStream; 019 020/** 021 * A BufferedOutputStream where the buffer is provided by a byte array. Use this class as an alternative to {@link java.io.BufferedOutputStream} 022 */ 023public class ByteArrayBufferedOutputStream extends AbstractBufferedOutputStream { 024 025 private byte[] buf; 026 027 /** 028 * Creates a new instance with the default buffer size 029 * @param out OutputStream to be decorated 030 * @see java.io.BufferedOutputStream#BufferedOutputStream(OutputStream) 031 */ 032 public ByteArrayBufferedOutputStream(OutputStream out) { 033 this(out, DEFAULT_BUFFER_SIZE); 034 } 035 036 /** 037 * Creates a new instance with the given buffer size in bytes. 038 * @param out OutputStream to be decorated 039 * @param size The size of the buffer in bytes 040 * @see java.io.BufferedOutputStream#BufferedOutputStream(OutputStream, int) 041 */ 042 public ByteArrayBufferedOutputStream(OutputStream out, int size) { 043 super(out); 044 if (size <= 0) { 045 throw new IllegalArgumentException("Buffer size <= 0"); 046 } 047 buf = new byte[size]; 048 } 049 050 @Override 051 protected byte[] bytes() { 052 return buf; 053 } 054 055 @Override 056 protected void put(byte b) { 057 put(b); 058 } 059 060 @Override 061 protected void put(int count, byte[] b, int off, int len) { 062 System.arraycopy(b, off, buf, count, len); 063 } 064 065 @Override 066 protected int limit() { 067 return buf.length; 068 } 069 070 @Override 071 protected void clean() { 072 if (buf == null) { 073 return; 074 } 075 076 buf = null; 077 } 078}