1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.io;
  17. import java.io.ByteArrayInputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.InputStreamReader;
  21. import java.io.OutputStream;
  22. import java.io.OutputStreamWriter;
  23. import java.io.Reader;
  24. import java.io.StringReader;
  25. import java.io.Writer;
  26. /**
  27. * <p>
  28. * This class provides static utility methods for buffered
  29. * copying between sources (<code>InputStream</code>, <code>Reader</code>, <code>String</code> and
  30. * <code>byte[]</code>) and destinations (<code>OutputStream</code>, <code>Writer</code>,
  31. * <code>String</code> and <code>byte[]</code>).
  32. * </p>
  33. *
  34. * <p>Unless otherwise noted, these <code>copy</code> methods do <em>not</em> flush or close the
  35. * streams. Often doing so would require making non-portable assumptions about the streams' origin
  36. * and further use. This means that both streams' <code>close()</code> methods must be called after
  37. * copying. if one omits this step, then the stream resources (sockets, file descriptors) are
  38. * released when the associated Stream is garbage-collected. It is not a good idea to rely on this
  39. * mechanism. For a good overview of the distinction between "memory management" and "resource
  40. * management", see <a href="http://www.unixreview.com/articles/1998/9804/9804ja/ja.htm">this
  41. * UnixReview article</a>.</p>
  42. *
  43. * <p>For byte-to-char methods, a <code>copy</code> variant allows the encoding
  44. * to be selected (otherwise the platform default is used). We would like to
  45. * encourage you to always specify the encoding because relying on the platform
  46. * default can lead to unexpected results.</p>
  47. *
  48. * <p>We don't provide special variants for the <code>copy</code> methods that
  49. * let you specify the buffer size because in modern VMs the impact on speed
  50. * seems to be minimal. We're using a default buffer size of 4 KB.</p>
  51. *
  52. * <p>The <code>copy</code> methods use an internal buffer when copying. It is therefore advisable
  53. * <em>not</em> to deliberately wrap the stream arguments to the <code>copy</code> methods in
  54. * <code>Buffered*</code> streams. For example, don't do the
  55. * following:</p>
  56. *
  57. * <code>copy( new BufferedInputStream( in ), new BufferedOutputStream( out ) );</code>
  58. *
  59. * <p>The rationale is as follows:</p>
  60. *
  61. * <p>Imagine that an InputStream's read() is a very expensive operation, which would usually suggest
  62. * wrapping in a BufferedInputStream. The BufferedInputStream works by issuing infrequent
  63. * {@link java.io.InputStream#read(byte[] b, int off, int len)} requests on the underlying InputStream, to
  64. * fill an internal buffer, from which further <code>read</code> requests can inexpensively get
  65. * their data (until the buffer runs out).</p>
  66. * <p>However, the <code>copy</code> methods do the same thing, keeping an internal buffer,
  67. * populated by {@link InputStream#read(byte[] b, int off, int len)} requests. Having two buffers
  68. * (or three if the destination stream is also buffered) is pointless, and the unnecessary buffer
  69. * management hurts performance slightly (about 3%, according to some simple experiments).</p>
  70. *
  71. * <p>Behold, intrepid explorers; a map of this class:</p>
  72. * <pre>
  73. * Method Input Output Dependency
  74. * ------ ----- ------ -------
  75. * 1 copy InputStream OutputStream (primitive)
  76. * 2 copy Reader Writer (primitive)
  77. *
  78. * 3 copy InputStream Writer 2
  79. *
  80. * 4 copy Reader OutputStream 2
  81. *
  82. * 5 copy String OutputStream 2
  83. * 6 copy String Writer (trivial)
  84. *
  85. * 7 copy byte[] Writer 3
  86. * 8 copy byte[] OutputStream (trivial)
  87. * </pre>
  88. *
  89. * <p>Note that only the first two methods shuffle bytes; the rest use these
  90. * two, or (if possible) copy using native Java copy methods. As there are
  91. * method variants to specify the encoding, each row may
  92. * correspond to up to 2 methods.</p>
  93. *
  94. * <p>Origin of code: Apache Avalon (Excalibur)</p>
  95. *
  96. * @author Peter Donald
  97. * @author Jeff Turner
  98. * @author Matthew Hawthorne
  99. * @version $Id: CopyUtils.java,v 1.6 2004/04/24 23:49:25 bayard Exp $
  100. */
  101. public class CopyUtils {
  102. /**
  103. * The name says it all.
  104. */
  105. private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
  106. /**
  107. * Instances should NOT be constructed in standard programming.
  108. */
  109. public CopyUtils() {}
  110. // ----------------------------------------------------------------
  111. // byte[] -> OutputStream
  112. // ----------------------------------------------------------------
  113. /**
  114. * Copy bytes from a <code>byte[]</code> to an <code>OutputStream</code>.
  115. * @param input the byte array to read from
  116. * @param output the <code>OutputStream</code> to write to
  117. * @throws IOException In case of an I/O problem
  118. */
  119. public static void copy(byte[] input, OutputStream output)
  120. throws IOException {
  121. output.write(input);
  122. }
  123. // ----------------------------------------------------------------
  124. // byte[] -> Writer
  125. // ----------------------------------------------------------------
  126. /**
  127. * Copy and convert bytes from a <code>byte[]</code> to chars on a
  128. * <code>Writer</code>.
  129. * The platform's default encoding is used for the byte-to-char conversion.
  130. * @param input the byte array to read from
  131. * @param output the <code>Writer</code> to write to
  132. * @throws IOException In case of an I/O problem
  133. */
  134. public static void copy(byte[] input, Writer output)
  135. throws IOException {
  136. ByteArrayInputStream in = new ByteArrayInputStream(input);
  137. copy(in, output);
  138. }
  139. /**
  140. * Copy and convert bytes from a <code>byte[]</code> to chars on a
  141. * <code>Writer</code>, using the specified encoding.
  142. * @param input the byte array to read from
  143. * @param output the <code>Writer</code> to write to
  144. * @param encoding The name of a supported character encoding. See the
  145. * <a href="http://www.iana.org/assignments/character-sets">IANA
  146. * Charset Registry</a> for a list of valid encoding types.
  147. * @throws IOException In case of an I/O problem
  148. */
  149. public static void copy(
  150. byte[] input,
  151. Writer output,
  152. String encoding)
  153. throws IOException {
  154. ByteArrayInputStream in = new ByteArrayInputStream(input);
  155. copy(in, output, encoding);
  156. }
  157. // ----------------------------------------------------------------
  158. // Core copy methods
  159. // ----------------------------------------------------------------
  160. /**
  161. * Copy bytes from an <code>InputStream</code> to an <code>OutputStream</code>.
  162. * @param input the <code>InputStream</code> to read from
  163. * @param output the <code>OutputStream</code> to write to
  164. * @return the number of bytes copied
  165. * @throws IOException In case of an I/O problem
  166. */
  167. public static int copy(
  168. InputStream input,
  169. OutputStream output)
  170. throws IOException {
  171. byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
  172. int count = 0;
  173. int n = 0;
  174. while (-1 != (n = input.read(buffer))) {
  175. output.write(buffer, 0, n);
  176. count += n;
  177. }
  178. return count;
  179. }
  180. // ----------------------------------------------------------------
  181. // Reader -> Writer
  182. // ----------------------------------------------------------------
  183. /**
  184. * Copy chars from a <code>Reader</code> to a <code>Writer</code>.
  185. * @param input the <code>Reader</code> to read from
  186. * @param output the <code>Writer</code> to write to
  187. * @return the number of characters copied
  188. * @throws IOException In case of an I/O problem
  189. */
  190. public static int copy(
  191. Reader input,
  192. Writer output)
  193. throws IOException {
  194. char[] buffer = new char[DEFAULT_BUFFER_SIZE];
  195. int count = 0;
  196. int n = 0;
  197. while (-1 != (n = input.read(buffer))) {
  198. output.write(buffer, 0, n);
  199. count += n;
  200. }
  201. return count;
  202. }
  203. // ----------------------------------------------------------------
  204. // InputStream -> Writer
  205. // ----------------------------------------------------------------
  206. /**
  207. * Copy and convert bytes from an <code>InputStream</code> to chars on a
  208. * <code>Writer</code>.
  209. * The platform's default encoding is used for the byte-to-char conversion.
  210. * @param input the <code>InputStream</code> to read from
  211. * @param output the <code>Writer</code> to write to
  212. * @throws IOException In case of an I/O problem
  213. */
  214. public static void copy(
  215. InputStream input,
  216. Writer output)
  217. throws IOException {
  218. InputStreamReader in = new InputStreamReader(input);
  219. copy(in, output);
  220. }
  221. /**
  222. * Copy and convert bytes from an <code>InputStream</code> to chars on a
  223. * <code>Writer</code>, using the specified encoding.
  224. * @param input the <code>InputStream</code> to read from
  225. * @param output the <code>Writer</code> to write to
  226. * @param encoding The name of a supported character encoding. See the
  227. * <a href="http://www.iana.org/assignments/character-sets">IANA
  228. * Charset Registry</a> for a list of valid encoding types.
  229. * @throws IOException In case of an I/O problem
  230. */
  231. public static void copy(
  232. InputStream input,
  233. Writer output,
  234. String encoding)
  235. throws IOException {
  236. InputStreamReader in = new InputStreamReader(input, encoding);
  237. copy(in, output);
  238. }
  239. // ----------------------------------------------------------------
  240. // Reader -> OutputStream
  241. // ----------------------------------------------------------------
  242. /**
  243. * Serialize chars from a <code>Reader</code> to bytes on an
  244. * <code>OutputStream</code>, and flush the <code>OutputStream</code>.
  245. * @param input the <code>Reader</code> to read from
  246. * @param output the <code>OutputStream</code> to write to
  247. * @throws IOException In case of an I/O problem
  248. */
  249. public static void copy(
  250. Reader input,
  251. OutputStream output)
  252. throws IOException {
  253. OutputStreamWriter out = new OutputStreamWriter(output);
  254. copy(input, out);
  255. // XXX Unless anyone is planning on rewriting OutputStreamWriter, we have to flush here.
  256. out.flush();
  257. }
  258. // ----------------------------------------------------------------
  259. // String -> OutputStream
  260. // ----------------------------------------------------------------
  261. /**
  262. * Serialize chars from a <code>String</code> to bytes on an <code>OutputStream</code>, and
  263. * flush the <code>OutputStream</code>.
  264. * @param input the <code>String</code> to read from
  265. * @param output the <code>OutputStream</code> to write to
  266. * @throws IOException In case of an I/O problem
  267. */
  268. public static void copy(
  269. String input,
  270. OutputStream output)
  271. throws IOException {
  272. StringReader in = new StringReader(input);
  273. OutputStreamWriter out = new OutputStreamWriter(output);
  274. copy(in, out);
  275. // XXX Unless anyone is planning on rewriting OutputStreamWriter, we have to flush here.
  276. out.flush();
  277. }
  278. // ----------------------------------------------------------------
  279. // String -> Writer
  280. // ----------------------------------------------------------------
  281. /**
  282. * Copy chars from a <code>String</code> to a <code>Writer</code>.
  283. * @param input the <code>String</code> to read from
  284. * @param output the <code>Writer</code> to write to
  285. * @throws IOException In case of an I/O problem
  286. */
  287. public static void copy(String input, Writer output)
  288. throws IOException {
  289. output.write(input);
  290. }
  291. } // CopyUtils