4 import java
.io
.FileInputStream
;
5 import java
.io
.IOException
;
6 import java
.nio
.ByteBuffer
;
7 import java
.nio
.channels
.FileChannel
;
10 public class FileComparator
implements FileNIONonDirectBufComparato
{
15 public FileComparator(int bufferSize
) {
16 this.bufferSize
= bufferSize
;
17 buffer1
= ByteBuffer
.allocate(bufferSize
);
18 buffer2
= ByteBuffer
.allocate(bufferSize
);
19 //System.out.println("Using: java.nio with non direct byte-buffers of size " + bufferSize + " bytes");
22 private int readIn(FileChannel f
, ByteBuffer buffer
) throws IOException
{
27 } while ((x
< bufferSize
) & (z
!= -1));
31 private static boolean compare(ByteBuffer a
, ByteBuffer b
, int len
) {
32 for(int i
= 0; i
< len
; i
++) if (a
.get(i
) != b
.get(i
)) return false;
36 public int compareFiles(File source1
, File source2
) throws IOException
{
37 FileInputStream s1
= null, s2
= null;
38 long source1Size
= source1
.length();
39 long source2Size
= source2
.length();
40 if (source1Size
!= source2Size
) return 1;
42 s1
= new FileInputStream(source1
);
43 s2
= new FileInputStream(source2
);
44 long alreadyReadedBytes
= 0;
46 while (alreadyReadedBytes
< source1Size
) {
49 int size1
= readIn(s1
.getChannel(), buffer1
);
50 /*int size2 = */readIn(s2
.getChannel(), buffer2
);
51 //assert (size1 != size2) :"Files have different sizes in contradiction to earlier check";
52 if (!compare(buffer1
, buffer2
, size1
)){
56 alreadyReadedBytes
+= size1
;
60 if (s1
!= null) s1
.close();
61 if (s2
!= null) s2
.close();
65 //public interface FileNIONonDirectBufComparator {
67 interface FileNIONonDirectBufComparato
{
68 public int compareFiles(File source1
, File source2
) throws IOException
;