001
014
015 package com.liferay.portal.kernel.io.unsync;
016
017 import java.io.IOException;
018 import java.io.OutputStream;
019
020
027 public class UnsyncBufferedOutputStream extends UnsyncFilterOutputStream {
028
029 public UnsyncBufferedOutputStream(OutputStream outputStream) {
030 this(outputStream, _DEFAULT_BUFFER_SIZE);
031 }
032
033 public UnsyncBufferedOutputStream(OutputStream outputStream, int size) {
034 super(outputStream);
035
036 if (size <= 0) {
037 throw new IllegalArgumentException("Size is less than 0");
038 }
039
040 buffer = new byte[size];
041 }
042
043 @Override
044 public void flush() throws IOException {
045 if (count > 0) {
046 outputStream.write(buffer, 0, count);
047
048 count = 0;
049 }
050
051 outputStream.flush();
052 }
053
054 @Override
055 public void write(byte[] bytes) throws IOException {
056 write(bytes, 0, bytes.length);
057 }
058
059 @Override
060 public void write(byte[] bytes, int offset, int length) throws IOException {
061 if (length >= buffer.length) {
062 if (count > 0) {
063 outputStream.write(buffer, 0, count);
064
065 count = 0;
066 }
067
068 outputStream.write(bytes, offset, length);
069
070 return;
071 }
072
073 if ((count > 0) && (length > (buffer.length - count))) {
074 outputStream.write(buffer, 0, count);
075
076 count = 0;
077 }
078
079 System.arraycopy(bytes, offset, buffer, count, length);
080
081 count += length;
082 }
083
084 @Override
085 public void write(int b) throws IOException {
086 if (count >= buffer.length) {
087 outputStream.write(buffer, 0, count);
088
089 count = 0;
090 }
091
092 buffer[count++] = (byte)b;
093 }
094
095 protected byte[] buffer;
096 protected int count;
097
098 private static final int _DEFAULT_BUFFER_SIZE = 8192;
099
100 }