Пример #1
0
  /**
   * Compares the contents of two streams by reading them.
   *
   * <p>NOTE: The streams get closed in any case.
   *
   * @param contents1 the first content stream
   * @param contents2 the second content stream
   * @return true iff both stream had the same length and the same data
   * @throws IOException if an I/O exception occurs while reading one of the streams
   */
  public static boolean hasSameContents(InputStream contents1, InputStream contents2)
      throws IOException {
    try {
      int bufSize = 10000;
      byte[] buffer1 = new byte[bufSize];
      byte[] buffer2 = new byte[bufSize];

      boolean eof1 = false;
      boolean eof2 = false;
      while (!eof1 && !eof2) {

        int pos1 = 0;
        while (pos1 != bufSize) {
          int count = contents1.read(buffer1, pos1, bufSize - pos1);
          if (count == -1) {
            eof1 = true;
            break;
          }
          pos1 += count;
        }

        int pos2 = 0;
        while (pos2 != bufSize) {
          int count = contents2.read(buffer2, pos2, bufSize - pos2);
          if (count == -1) {
            eof2 = true;
            break;
          }
          pos2 += count;
        }

        if (eof1 || eof2) {
          if (pos1 != pos2 || !firstBytesEquals(buffer1, buffer2, pos1)) {
            return false;
          }
        } else {
          if (!Arrays.equals(buffer1, buffer2)) {
            return false;
          }
        }
      }

      return true;
    } finally {
      IOUtil.closeSilently(contents1);
      IOUtil.closeSilently(contents2);
    }
  }
Пример #2
0
 /**
  * Copies the data from the given input stream to the given output stream. Closes both streams in
  * any case.
  *
  * @param in stream to read from
  * @param out stream to write to
  * @throws IOException if any I/O exception occurs during reading or writing
  */
 public static final void copyInputStreamToOutputStream(InputStream in, OutputStream out)
     throws IOException {
   byte[] buffer = new byte[1024 * 4];
   try {
     int len;
     while ((len = in.read(buffer)) >= 0) {
       out.write(buffer, 0, len);
     }
   } finally {
     closeSilently(in);
     closeSilently(out);
   }
 }