1 19 20 package org.apache.avalon.fortress.tools; 21 22 import java.io.ByteArrayOutputStream ; 23 import java.io.File ; 24 import java.io.FileInputStream ; 25 import java.io.FileOutputStream ; 26 import java.io.IOException ; 27 import java.io.OutputStream ; 28 29 37 public final class ChangedFileOutputStream 38 extends OutputStream 39 { 40 41 private File m_file; 42 43 44 private ByteArrayOutputStream m_bos; 45 46 49 54 public ChangedFileOutputStream( File file ) 55 { 56 m_file = file; 57 m_bos = new ByteArrayOutputStream (); 58 } 59 60 63 70 public void write( int b ) 71 throws IOException 72 { 73 m_bos.write( b ); 74 } 75 76 81 public void close() 82 throws IOException 83 { 84 byte[] newContent = m_bos.toByteArray(); 85 m_bos.close(); 86 87 boolean changed; 88 if ( m_file.exists() ) 89 { 90 byte[] oldContent = readBytes( m_file ); 91 92 if ( newContent.length != oldContent.length ) 94 { 95 changed = true; 96 } 97 else 98 { 99 changed = false; 100 for ( int i = 0; i < newContent.length; i++ ) 101 { 102 if ( newContent[i] != oldContent[i] ) 103 { 104 changed = true; 105 break; 106 } 107 } 108 } 109 } 110 else 111 { 112 changed = true; 114 } 115 116 if ( changed ) 117 { 118 writeBytes( m_file, newContent ); 119 } 120 } 121 122 125 135 private byte[] readBytes( File file ) 136 throws IOException 137 { 138 byte[] bytes = new byte[(int)file.length()]; 139 140 FileInputStream is = new FileInputStream ( file ); 141 try 142 { 143 int pos = 0; 145 int read; 146 while ( ( pos < bytes.length ) && 147 ( ( read = is.read( bytes, pos, bytes.length - pos ) ) >= 0 ) ) 148 { 149 pos += read; 150 } 151 } 152 finally 153 { 154 is.close(); 155 } 156 157 return bytes; 158 } 159 160 168 private void writeBytes( File file, byte[] bytes ) 169 throws IOException 170 { 171 FileOutputStream os = new FileOutputStream ( file ); 172 try 173 { 174 os.write( bytes, 0, bytes.length ); 175 } 176 finally 177 { 178 os.close(); 179 } 180 } 181 } 182 | Popular Tags |