1 4 package com.tc; 5 6 import org.apache.commons.io.IOUtils; 7 8 import java.io.BufferedReader ; 9 import java.io.File ; 10 import java.io.FileInputStream ; 11 import java.io.IOException ; 12 import java.io.InputStreamReader ; 13 import java.io.Reader ; 14 import java.util.ArrayList ; 15 import java.util.ConcurrentModificationException ; 16 17 public class TextLineInfo implements java.io.Serializable { 18 private int[] m_lines; 19 20 public TextLineInfo() { 21 super(); 22 } 23 24 public TextLineInfo(File file) 25 throws ConcurrentModificationException , 26 IOException 27 { 28 this(); 29 setFile(file); 30 } 31 32 public TextLineInfo(Reader reader) 33 throws ConcurrentModificationException , 34 IOException 35 { 36 this(); 37 setReader(reader); 38 } 39 40 public void setFile(File file) 41 throws ConcurrentModificationException , 42 IOException 43 { 44 initLines(new InputStreamReader (new FileInputStream (file))); 45 } 46 47 public void setReader(Reader reader) 48 throws ConcurrentModificationException , 49 IOException 50 { 51 initLines(reader); 52 } 53 54 private void initLines(Reader reader) 55 throws ConcurrentModificationException , 56 IOException 57 { 58 ArrayList list = new ArrayList (); 59 60 try { 61 BufferedReader br = new BufferedReader (reader); 62 String s; 63 64 while((s = br.readLine()) != null) { 65 list.add(s); 66 } 67 } catch(IOException e) { 68 IOUtils.closeQuietly(reader); 69 throw e; 70 } catch(ConcurrentModificationException e) { 71 IOUtils.closeQuietly(reader); 72 throw e; 73 } finally { 74 IOUtils.closeQuietly(reader); 75 } 76 77 int size = list.size(); 78 m_lines = new int[size]; 79 for(int i = 0; i < size; i++) { 80 m_lines[i] = ((String )list.get(i)).length()+1; 81 } 82 } 83 84 public int lineSize(int line) { 85 if(line < 0 || line > m_lines.length) { 86 return 0; 87 } 88 return m_lines[line]; 89 } 90 91 public int offset(int line) { 92 int result = 0; 93 94 if(line == 0) return 0; 95 96 for(int i = 0; i < line; i++) { 97 result += m_lines[i]; 98 } 99 100 return result; 101 } 102 103 public int offset(int line, int col) { 104 if(line < 0 || line > m_lines.length) { 105 return 0; 106 } 107 int result = offset(line); 108 if(col > 0) { 109 result += col; 110 } 111 return result; 112 } 113 } 114 | Popular Tags |