1 36 package org.columba.ristretto.io; 37 38 import java.io.File ; 39 import java.io.IOException ; 40 41 47 public class FileSource implements Source { 48 49 private int start, end; 50 private int pos; 51 52 private FileSourceModel model; 53 54 55 61 public FileSource( File file ) throws IOException { 62 model = new FileSourceModel( file ); 63 model.incReferences(); 64 start = 0; 65 end = model.length(); 66 pos = 0; 67 } 68 69 protected FileSource( FileSource parent ) { 70 this.model = parent.model; 71 this.model.incReferences(); 72 this.start = parent.start; 73 this.end = parent.end; 74 this.pos = 0; 75 } 76 77 80 public Source fromActualPosition() { 81 FileSource subsource = new FileSource( this ); 82 subsource.start = start + pos; 83 84 return subsource; 85 } 86 87 90 public int getPosition() { 91 return pos; 92 } 93 94 97 public void seek(int position) throws IOException { 98 pos = position; 99 } 100 101 104 public char next() throws IOException { 105 return model.get(start + pos++); 106 } 107 108 111 public int length() { 112 return end - start; 113 } 114 115 118 public char charAt(int arg0){ 119 try { 120 return model.get(start + arg0); 121 } catch (IOException e) { 122 e.printStackTrace(); 123 return 0; 124 } 125 } 126 127 130 public Source subSource(int arg0, int arg1) { 131 FileSource subsource = new FileSource( this ); 132 subsource.start = start + arg0; 133 subsource.end = start + arg1; 134 return subsource; 135 } 136 137 140 public CharSequence subSequence(int arg0, int arg1) { 141 if( arg1 - arg0 < 1024) { 142 StringBuffer result = new StringBuffer ( arg1- arg0); 143 for( int i=arg0; i<arg1; i++ ) { 144 result.append(charAt(i)); 145 } 146 return result; 147 } else { 148 return subSource( arg0, arg1); 149 } 150 } 151 152 155 public String toString() { 156 StringBuffer buffer = new StringBuffer (length()); 157 for( int i=0; i < length(); i++) { 158 buffer.append(charAt(i)); 159 } 160 return buffer.toString(); 161 } 162 163 164 165 168 public boolean isEOF() { 169 return pos == end; 170 } 171 172 173 174 177 protected void finalize() throws Throwable { 178 super.finalize(); 179 if( model != null ) { 180 model.decReferences(); 181 model = null; 182 } 183 } 184 187 public void close() throws IOException { 188 if( model != null ) { 189 model.decReferences(); 190 model = null; 191 } 192 } 193 194 197 public void deepClose() throws IOException { 198 if ( model != null) 199 model.close(); 200 model = null; 201 } 202 203 208 public File getFile() { 209 return model.getFile(); 210 } 211 } 212 | Popular Tags |