| 1 8 9 package beaver.comp.io; 10 11 import java.io.File ; 12 import java.io.FileReader ; 13 import java.io.IOException ; 14 import java.io.Reader ; 15 16 import beaver.comp.util.IntArray; 17 18 21 public class SrcReader extends Reader  22 { 23 public final File file; 24 25 protected char[] txt; 26 protected IntArray lines; 27 28 private int ptr; 29 30 public SrcReader(File src_file) throws IOException  31 { 32 super(); 33 this.file = src_file; 34 35 Reader txt_reader = new FileReader (src_file); 36 try 37 { 38 txt = new char[(int) src_file.length()]; 39 txt_reader.read(txt); 40 } 41 finally 42 { 43 txt_reader.close(); 44 } 45 lines = new IntArray(txt.length / 20 + 20); 46 47 boolean eol = true, cr = false; 48 for (int i = 0; i < txt.length; i++) 49 { 50 if (eol) 51 { 52 lines.add(i); 53 eol = false; 54 } 55 switch (txt[i]) 56 { 57 case '\u000B': 58 case '\u000C': 59 case '\u0085': 60 case '\u2028': 61 case '\u2029': 62 { 63 eol = true; 64 cr = false; 65 break; 66 } 67 case '\r': 68 { 69 if (cr) 70 eol = true; 71 cr = true; 72 break; 73 } 74 case '\n': 75 { 76 if (cr) 77 cr = false; 78 eol = true; 79 break; 80 } 81 default: 82 { 83 if (cr) 84 eol = true; 85 cr = false; 86 } 87 } 88 } 89 } 90 91 public int read(char[] buf, int off, int len) 92 { 93 int copy_max = txt.length - ptr; 94 if (copy_max <= 0) 95 return -1; 96 int copy_len = Math.min(copy_max, len); 97 if (copy_len > 0) 98 { 99 System.arraycopy(txt, ptr, buf, off, copy_len); 100 ptr += copy_len; 101 } 102 return copy_len; 103 } 104 105 public void reset() 106 { 107 ptr = 0; 108 } 109 110 public void close() 111 { 112 } 113 114 public String getLine(int n) 115 { 116 int line_start = lines.get(n - 1); 117 int line_len = (n == lines.size() ? txt.length : lines.get(n)) - line_start; 118 return new String (txt, line_start, line_len); 119 } 120 } | Popular Tags |