View Javadoc

1   /*
2    * #%L
3    * Bitmagasin Protocol
4    * 
5    * $Id$
6    * $HeadURL$
7    * %%
8    * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark
9    * %%
10   * This program is free software: you can redistribute it and/or modify
11   * it under the terms of the GNU Lesser General Public License as 
12   * published by the Free Software Foundation, either version 2.1 of the 
13   * License, or (at your option) any later version.
14   * 
15   * This program is distributed in the hope that it will be useful,
16   * but WITHOUT ANY WARRANTY; without even the implied warranty of
17   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18   * GNU General Lesser Public License for more details.
19   * 
20   * You should have received a copy of the GNU General Lesser Public 
21   * License along with this program.  If not, see
22   * <http://www.gnu.org/licenses/lgpl-2.1.html>.
23   * #L%
24   */
25  package org.bitrepository.common.utils;
26  
27  import java.io.IOException;
28  import java.io.InputStream;
29  import java.io.OutputStream;
30  
31  /**
32   * Utility class for handling standard stream issues.
33   */
34  public final class StreamUtils {
35      /** Private constructor to prevent instantiation of this utility class.*/
36      private StreamUtils() {}
37      
38      /** The default buffer size. 32 kb. */
39      private static final int IO_BUFFER_SIZE = 32*1024;
40      
41      /**
42       * Utility function for moving data from an inputstream to an outputstream.
43       * TODO move to a utility class.
44       * 
45       * @param in The input stream to copy to the output stream.
46       * @param out The output stream where the input stream should be copied.
47       * @throws IOException If anything problems occur with transferring the 
48       * data between the streams.
49       */
50      public static void copyInputStreamToOutputStream(InputStream in,
51              OutputStream out) throws IOException {
52          if(in == null || out == null) {
53              throw new IllegalArgumentException("InputStream: " + in 
54                      + ", OutputStream: " + out);
55          }
56          
57          try {
58              byte[] buf = new byte[IO_BUFFER_SIZE];
59              int bytesRead;
60              while ((bytesRead = in.read(buf)) != -1) {
61                  out.write(buf, 0, bytesRead);
62              }
63              out.flush();
64          } finally {
65              in.close();
66          }
67      }
68      
69  }