1 7 8 package java.io; 9 10 11 30 31 public class LineNumberReader extends BufferedReader { 32 33 34 private int lineNumber = 0; 35 36 37 private int markedLineNumber; 39 40 private boolean skipLF; 41 42 43 private boolean markedSkipLF; 44 45 51 public LineNumberReader(Reader in) { 52 super(in); 53 } 54 55 62 public LineNumberReader(Reader in, int sz) { 63 super(in, sz); 64 } 65 66 72 public void setLineNumber(int lineNumber) { 73 this.lineNumber = lineNumber; 74 } 75 76 82 public int getLineNumber() { 83 return lineNumber; 84 } 85 86 95 public int read() throws IOException { 96 synchronized (lock) { 97 int c = super.read(); 98 if (skipLF) { 99 if (c == '\n') 100 c = super.read(); 101 skipLF = false; 102 } 103 switch (c) { 104 case '\r': 105 skipLF = true; 106 case '\n': 107 lineNumber++; 108 return '\n'; 109 } 110 return c; 111 } 112 } 113 114 126 public int read(char cbuf[], int off, int len) throws IOException { 127 synchronized (lock) { 128 int n = super.read(cbuf, off, len); 129 130 for (int i = off; i < off + n; i++) { 131 int c = cbuf[i]; 132 if (skipLF) { 133 skipLF = false; 134 if (c == '\n') 135 continue; 136 } 137 switch (c) { 138 case '\r': 139 skipLF = true; 140 case '\n': 141 lineNumber++; 142 break; 143 } 144 } 145 146 return n; 147 } 148 } 149 150 161 public String readLine() throws IOException { 162 synchronized (lock) { 163 String l = super.readLine(skipLF); 164 skipLF = false; 165 if (l != null) 166 lineNumber++; 167 return l; 168 } 169 } 170 171 172 private static final int maxSkipBufferSize = 8192; 173 174 175 private char skipBuffer[] = null; 176 177 188 public long skip(long n) throws IOException { 189 if (n < 0) 190 throw new IllegalArgumentException ("skip() value is negative"); 191 int nn = (int) Math.min(n, maxSkipBufferSize); 192 synchronized (lock) { 193 if ((skipBuffer == null) || (skipBuffer.length < nn)) 194 skipBuffer = new char[nn]; 195 long r = n; 196 while (r > 0) { 197 int nc = read(skipBuffer, 0, (int) Math.min(r, nn)); 198 if (nc == -1) 199 break; 200 r -= nc; 201 } 202 return n - r; 203 } 204 } 205 206 218 public void mark(int readAheadLimit) throws IOException { 219 synchronized (lock) { 220 super.mark(readAheadLimit); 221 markedLineNumber = lineNumber; 222 markedSkipLF = skipLF; 223 } 224 } 225 226 232 public void reset() throws IOException { 233 synchronized (lock) { 234 super.reset(); 235 lineNumber = markedLineNumber; 236 skipLF = markedSkipLF; 237 } 238 } 239 240 } 241 | Popular Tags |