1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portal.kernel.io.unsync;
16  
17  import java.io.IOException;
18  import java.io.OutputStream;
19  
20  /**
21   * <a href="UnsyncBufferedOutputStream.java.html"><b><i>View Source</i></b></a>
22   *
23   * <p>
24   * See http://issues.liferay.com/browse/LPS-6648.
25   * </p>
26   *
27   * @author Shuyang Zhou
28   */
29  public class UnsyncBufferedOutputStream extends UnsyncFilterOutputStream {
30  
31      public UnsyncBufferedOutputStream(OutputStream outputStream) {
32          this(outputStream, _DEFAULT_BUFFER_SIZE);
33      }
34  
35      public UnsyncBufferedOutputStream(OutputStream outputStream, int size) {
36          super(outputStream);
37  
38          buffer = new byte[size];
39      }
40  
41      public void flush() throws IOException {
42          if (count > 0) {
43              outputStream.write(buffer, 0, count);
44  
45              count = 0;
46          }
47  
48          outputStream.flush();
49      }
50  
51      public void write(byte[] byteArray, int offset, int length)
52          throws IOException {
53  
54          if (length >= buffer.length) {
55              if (count > 0) {
56                  outputStream.write(buffer, 0, count);
57  
58                  count = 0;
59              }
60  
61              outputStream.write(byteArray, offset, length);
62  
63              return;
64          }
65  
66          if (count > 0 && length > buffer.length - count) {
67              outputStream.write(buffer, 0, count);
68  
69              count = 0;
70          }
71  
72          System.arraycopy(byteArray, offset, buffer, count, length);
73  
74          count += length;
75      }
76  
77      public void write(byte[] byteArray) throws IOException {
78          write(byteArray, 0, byteArray.length);
79      }
80  
81      public void write(int b) throws IOException {
82          if (count >= buffer.length) {
83              outputStream.write(buffer, 0, count);
84  
85              count = 0;
86          }
87  
88          buffer[count++] = (byte)b;
89      }
90  
91      protected byte[] buffer;
92      protected int count;
93  
94      private static int _DEFAULT_BUFFER_SIZE = 8192;
95  
96  }