1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.io.channels;
19
20 import java.io.IOException;
21 import java.nio.ByteBuffer;
22 import java.nio.channels.FileChannel;
23 import java.util.Objects;
24
25 import org.apache.commons.io.IOUtils;
26
27
28
29
30
31
32 public final class FileChannels {
33
34
35
36
37
38
39
40
41
42
43 public static boolean contentEquals(final FileChannel channel1, final FileChannel channel2, final int byteBufferSize) throws IOException {
44
45 if (Objects.equals(channel1, channel2)) {
46 return true;
47 }
48
49 final long size1 = size(channel1);
50 final long size2 = size(channel2);
51 if (size1 != size2) {
52 return false;
53 }
54 if (size1 == 0 && size2 == 0) {
55 return true;
56 }
57
58 final ByteBuffer byteBuffer1 = ByteBuffer.allocateDirect(byteBufferSize);
59 final ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(byteBufferSize);
60 while (true) {
61 final int read1 = channel1.read(byteBuffer1);
62 final int read2 = channel2.read(byteBuffer2);
63 byteBuffer1.clear();
64 byteBuffer2.clear();
65 if (read1 == IOUtils.EOF && read2 == IOUtils.EOF) {
66 return byteBuffer1.equals(byteBuffer2);
67 }
68 if (read1 != read2) {
69 return false;
70 }
71 if (!byteBuffer1.equals(byteBuffer2)) {
72 return false;
73 }
74 }
75 }
76
77 private static long size(final FileChannel channel) throws IOException {
78 return channel != null ? channel.size() : 0;
79 }
80
81
82
83
84 private FileChannels() {
85
86 }
87 }