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, int offset, int length) throws IOException {
056 if (length >= buffer.length) {
057 if (count > 0) {
058 outputStream.write(buffer, 0, count);
059
060 count = 0;
061 }
062
063 outputStream.write(bytes, offset, length);
064
065 return;
066 }
067
068 if (count > 0 && length > buffer.length - count) {
069 outputStream.write(buffer, 0, count);
070
071 count = 0;
072 }
073
074 System.arraycopy(bytes, offset, buffer, count, length);
075
076 count += length;
077 }
078
079 @Override
080 public void write(byte[] bytes) throws IOException {
081 write(bytes, 0, bytes.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 int _DEFAULT_BUFFER_SIZE = 8192;
099
100 }