*** empty log message ***
[thera-pi-2.git] / Reha / src / systemTools / FileComparator.java
blob0bb4454cb7bd7118aab3a63ccbd7e545b5c632c6
1 package systemTools;
3 import java.io.File;
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 {
11 int bufferSize;
12 ByteBuffer buffer1;
13 ByteBuffer buffer2;
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 {
23 int x = 0, z = 0;
24 do {
25 x+=z;
26 z = f.read(buffer);
27 } while ((x < bufferSize) & (z != -1));
28 return x;
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;
33 return true;
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;
41 try {
42 s1 = new FileInputStream(source1);
43 s2 = new FileInputStream(source2);
44 long alreadyReadedBytes = 0;
46 while (alreadyReadedBytes < source1Size) {
47 buffer1.clear();
48 buffer2.clear();
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)){
54 return 2;
56 alreadyReadedBytes += size1;
58 return 0;
59 } finally {
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;