001package org.avaje.dbmigration.util;
002
003import java.io.ByteArrayOutputStream;
004import java.io.IOException;
005import java.io.InputStream;
006import java.io.OutputStream;
007import java.io.UnsupportedEncodingException;
008
009/**
010 * Utilities for IO.
011 */
012public class IOUtils {
013
014  /**
015   * Reads the entire contents of the specified input stream and returns them
016   * as UTF-8 string.
017   */
018  public static String readUtf8(InputStream in) throws IOException {
019    return bytesToUtf8(read(in));
020  }
021
022  /**
023   * Reads the entire contents of the specified input stream and returns them
024   * as a byte array.
025   */
026  private static byte[] read(InputStream in) throws IOException {
027    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
028    pump(in, buffer);
029    return buffer.toByteArray();
030  }
031
032  /**
033   * Returns the UTF-8 string corresponding to the specified bytes.
034   */
035  private static String bytesToUtf8(byte[] data) {
036    try {
037      return new String(data, "UTF-8");
038    } catch (UnsupportedEncodingException e) {
039      throw new IllegalStateException("Support for UTF-8 is mandated by the Java spec", e);
040    }
041  }
042
043  /**
044   * Reads data from the specified input stream and copies it to the specified
045   * output stream, until the input stream is at EOF. Both streams are then
046   * closed.
047   */
048  private static void pump(InputStream in, OutputStream out) throws IOException {
049
050    if (in == null) throw new IOException("Input stream is null");
051    if (out == null) throw new IOException("Output stream is null");
052    try {
053      try {
054        byte[] buffer = new byte[4096];
055        for (; ; ) {
056          int bytes = in.read(buffer);
057          if (bytes < 0) {
058            break;
059          }
060          out.write(buffer, 0, bytes);
061        }
062      } finally {
063        in.close();
064      }
065    } finally {
066      out.close();
067    }
068  }
069}