1 19 20 package org.netbeans.modules.schema2beansdev.gen; 21 22 import java.util.*; 23 import java.io.*; 24 25 public class WriteIfDifferentOutputStream extends OutputStream { 26 private RandomAccessFile randFile; 27 private long initialRandFileLength; 28 private boolean justWrite = false; 29 30 public WriteIfDifferentOutputStream(RandomAccessFile randFile) throws IOException { 31 this.randFile = randFile; 32 this.initialRandFileLength = randFile.length(); 33 } 34 35 public WriteIfDifferentOutputStream(String filename) throws IOException { 36 this(new RandomAccessFile(filename, "rw")); } 38 39 public WriteIfDifferentOutputStream(File file) throws IOException { 40 this(new RandomAccessFile(file, "rw")); } 42 43 public void write(int b) throws IOException { 44 if (justWrite) { 45 randFile.write(b); 46 return; 47 } 48 long fp = randFile.getFilePointer(); 49 if (fp + 1 > initialRandFileLength) { 50 justWrite = true; 51 randFile.write(b); 52 return; 53 } 54 int fromFile = randFile.read(); 55 if (fromFile != b) { 56 randFile.seek(fp); 58 randFile.write(b); 59 justWrite = true; 60 return; 61 } 62 } 63 64 private byte[] writeBuf; 65 private int lastLen = -1; 66 public void write(byte[] b, int off, int len) throws IOException { 67 if (justWrite) { 68 randFile.write(b, off, len); 69 return; 70 } 71 long fp = randFile.getFilePointer(); 72 if (fp + len > initialRandFileLength) { 73 justWrite = true; 74 randFile.write(b, off, len); 75 return; 76 } 77 if (len > lastLen) { 78 writeBuf = new byte[len]; 80 lastLen = len; 81 } 82 randFile.read(writeBuf, 0, len); 83 for (int i = off, j = 0; j < len; ++i, ++j) { 84 if (writeBuf[j] != b[i]) { 85 randFile.seek(fp); 87 randFile.write(b, off, len); 88 justWrite = true; 89 return; 90 } 91 } 92 } 93 94 99 100 104 public boolean isChanged() { 105 return justWrite; 106 } 107 108 public void close() throws IOException { 109 if (randFile.getFilePointer() < randFile.length()) { 112 justWrite = true; 113 randFile.setLength(randFile.getFilePointer()); 114 } 115 randFile.close(); 116 } 117 } 118 | Popular Tags |