1 package persistence.antlr; 2 3 9 10 import java.io.*; 11 12 17 public class PreservingFileWriter extends FileWriter { 18 protected File target_file; protected File tmp_file; 21 public PreservingFileWriter(String file) throws IOException 22 { 23 super(file+".antlr.tmp"); 24 25 target_file = new File(file); 27 28 String parentdirname = target_file.getParent(); 29 if( parentdirname != null ) 30 { 31 File parentdir = new File(parentdirname); 32 33 if (!parentdir.exists()) 34 throw new IOException("destination directory of '"+file+"' doesn't exist"); 35 if (!parentdir.canWrite()) 36 throw new IOException("destination directory of '"+file+"' isn't writeable"); 37 } 38 if( target_file.exists() && ! target_file.canWrite() ) 39 throw new IOException("cannot write to '"+file+"'"); 40 41 tmp_file = new File(file+".antlr.tmp"); 43 } 49 50 53 public void close() throws IOException 54 { 55 Reader source = null; 56 Writer target = null; 57 58 try { 59 super.close(); 61 62 char[] buffer = new char[1024]; 63 int cnt; 64 65 if( target_file.length() == tmp_file.length() ) 67 { 68 Reader tmp; 70 char[] buf2 = new char[1024]; 71 72 source = new BufferedReader(new FileReader(tmp_file)); 73 tmp = new BufferedReader(new FileReader(target_file)); 74 int cnt1, cnt2; 75 boolean equal = true; 76 77 while( equal ) 78 { 79 cnt1 = source.read(buffer,0,1024); 80 cnt2 = tmp.read(buf2,0,1024); 81 if( cnt1 != cnt2 ) 82 { 83 equal = false; 84 break; 85 } 86 if( cnt1 == -1 ) break; 88 for( int i = 0; i < cnt1; i++ ) 89 { 90 if( buffer[i] != buf2[i] ) 91 { 92 equal = false; 93 break; 94 } 95 } 96 } 97 source.close(); 99 tmp.close(); 100 101 source = tmp = null; 102 103 if( equal ) 104 return; 105 } 106 107 source = new BufferedReader(new FileReader(tmp_file)); 108 target = new BufferedWriter(new FileWriter(target_file)); 109 110 while(true) 111 { 112 cnt = source.read(buffer,0,1024); 113 if( cnt == -1 ) 114 break; 115 target.write(buffer, 0, cnt ); 116 } 117 } 118 finally { 119 if( source != null ) 120 { 121 try { source.close(); } 122 catch( IOException e ) { ; } 123 } 124 if( target != null ) 125 { 126 try { target.close(); } 127 catch( IOException e ) { ; } 128 } 129 if( tmp_file != null && tmp_file.exists() ) 131 { 132 tmp_file.delete(); 133 tmp_file = null; 134 } 135 } 136 } 137 } 138 | Popular Tags |