FileChannels.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.io.channels;

  18. import java.io.IOException;
  19. import java.nio.ByteBuffer;
  20. import java.nio.channels.FileChannel;
  21. import java.nio.channels.ReadableByteChannel;
  22. import java.nio.channels.SeekableByteChannel;
  23. import java.util.Objects;

  24. import org.apache.commons.io.IOUtils;

  25. /**
  26.  * Works with {@link FileChannel}.
  27.  *
  28.  * @since 2.15.0
  29.  */
  30. public final class FileChannels {

  31.     /**
  32.      * Tests if two file channel contents are equal starting at their respective current positions.
  33.      *
  34.      * @param channel1       A file channel.
  35.      * @param channel2       Another file channel.
  36.      * @param bufferCapacity The two internal buffer capacities, in bytes.
  37.      * @return true if the contents of both RandomAccessFiles are equal, false otherwise.
  38.      * @throws IOException if an I/O error occurs.
  39.      * @deprecated Use {@link #contentEquals(SeekableByteChannel, SeekableByteChannel, int)}.
  40.      */
  41.     @Deprecated
  42.     public static boolean contentEquals(final FileChannel channel1, final FileChannel channel2, final int bufferCapacity) throws IOException {
  43.         return contentEquals((SeekableByteChannel) channel1, channel2, bufferCapacity);
  44.     }

  45.     /**
  46.      * Tests if two readable byte channel contents are equal starting at their respective current positions.
  47.      *
  48.      * @param channel1       A readable byte channel.
  49.      * @param channel2       Another readable byte channel.
  50.      * @param bufferCapacity The two internal buffer capacities, in bytes.
  51.      * @return true if the contents of both RandomAccessFiles are equal, false otherwise.
  52.      * @throws IOException if an I/O error occurs or the timeout is met.
  53.      * @since 2.19.0
  54.      */
  55.     public static boolean contentEquals(final ReadableByteChannel channel1, final ReadableByteChannel channel2, final int bufferCapacity) throws IOException {
  56.         // Before making any changes, please test with org.apache.commons.io.jmh.IOUtilsContentEqualsInputStreamsBenchmark
  57.         // Short-circuit test
  58.         if (Objects.equals(channel1, channel2)) {
  59.             return true;
  60.         }
  61.         // Don't use ByteBuffer#compact() to avoid extra copying.
  62.         final ByteBuffer c1Buffer = ByteBuffer.allocateDirect(bufferCapacity);
  63.         final ByteBuffer c2Buffer = ByteBuffer.allocateDirect(bufferCapacity);
  64.         int c1NumRead = 0;
  65.         int c2NumRead = 0;
  66.         boolean c1Read0 = false;
  67.         boolean c2Read0 = false;
  68.         // If a channel is a non-blocking channel, it may return 0 bytes read for any given call.
  69.         while (true) {
  70.             if (!c2Read0) {
  71.                 c1NumRead = readToLimit(channel1, c1Buffer);
  72.                 c1Buffer.clear();
  73.                 c1Read0 = c1NumRead == 0;
  74.             }
  75.             if (!c1Read0) {
  76.                 c2NumRead = readToLimit(channel2, c2Buffer);
  77.                 c2Buffer.clear();
  78.                 c2Read0 = c2NumRead == 0;
  79.             }
  80.             if (c1NumRead == IOUtils.EOF && c2NumRead == IOUtils.EOF) {
  81.                 return c1Buffer.equals(c2Buffer);
  82.             }
  83.             if (c1NumRead == 0 || c2NumRead == 0) {
  84.                 // 0 may be returned from a non-blocking channel.
  85.                 Thread.yield();
  86.                 continue;
  87.             }
  88.             if (c1NumRead != c2NumRead) {
  89.                 return false;
  90.             }
  91.             if (!c1Buffer.equals(c2Buffer)) {
  92.                 return false;
  93.             }
  94.         }
  95.     }

  96.     /**
  97.      * Tests if two seekable byte channel contents are equal starting at their respective current positions.
  98.      * <p>
  99.      * If the two channels have different sizes, no content comparison takes place, and this method returns false.
  100.      * </p>
  101.      *
  102.      * @param channel1       A seekable byte channel.
  103.      * @param channel2       Another seekable byte channel.
  104.      * @param bufferCapacity The two internal buffer capacities, in bytes.
  105.      * @return true if the contents of both RandomAccessFiles are equal, false otherwise.
  106.      * @throws IOException if an I/O error occurs or the timeout is met.
  107.      * @since 2.19.0
  108.      */
  109.     public static boolean contentEquals(final SeekableByteChannel channel1, final SeekableByteChannel channel2, final int bufferCapacity) throws IOException {
  110.         // Short-circuit test
  111.         if (Objects.equals(channel1, channel2)) {
  112.             return true;
  113.         }
  114.         // Short-circuit test
  115.         final long size1 = size(channel1);
  116.         final long size2 = size(channel2);
  117.         if (size1 != size2) {
  118.             return false;
  119.         }
  120.         return size1 == 0 && size2 == 0 || contentEquals((ReadableByteChannel) channel1, channel2, bufferCapacity);
  121.     }

  122.     /**
  123.      * Reads a sequence of bytes from a channel into the given buffer until the buffer reaches its limit or the channel has reaches end-of-stream.
  124.      * <p>
  125.      * The buffer's limit is not changed.
  126.      * </p>
  127.      *
  128.      * @param channel The source channel.
  129.      * @param dst     The buffer into which bytes are to be transferred.
  130.      * @return The number of bytes read, <em>never</em> zero, or {@code -1} if the channel has reached end-of-stream
  131.      * @throws IOException              If some other I/O error occurs.
  132.      * @throws IllegalArgumentException If there is room in the given buffer.
  133.      */
  134.     private static int readToLimit(final ReadableByteChannel channel, final ByteBuffer dst) throws IOException {
  135.         if (!dst.hasRemaining()) {
  136.             throw new IllegalArgumentException();
  137.         }
  138.         int totalRead = 0;
  139.         while (dst.hasRemaining()) {
  140.             final int numRead;
  141.             if ((numRead = channel.read(dst)) == IOUtils.EOF) {
  142.                 break;
  143.             }
  144.             if (numRead == 0) {
  145.                 // 0 may be returned from a non-blocking channel.
  146.                 Thread.yield();
  147.             } else {
  148.                 totalRead += numRead;
  149.             }
  150.         }
  151.         return totalRead != 0 ? totalRead : IOUtils.EOF;
  152.     }

  153.     private static long size(final SeekableByteChannel channel) throws IOException {
  154.         return channel != null ? channel.size() : 0;
  155.     }

  156.     /**
  157.      * Don't instantiate.
  158.      */
  159.     private FileChannels() {
  160.         // no-op
  161.     }
  162. }