001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package com.tc;
005:
006: import org.apache.commons.io.IOUtils;
007:
008: import java.io.BufferedReader;
009: import java.io.File;
010: import java.io.FileInputStream;
011: import java.io.IOException;
012: import java.io.InputStreamReader;
013: import java.io.Reader;
014: import java.util.ArrayList;
015: import java.util.ConcurrentModificationException;
016:
017: public class TextLineInfo implements java.io.Serializable {
018: private int[] m_lines;
019:
020: public TextLineInfo() {
021: super ();
022: }
023:
024: public TextLineInfo(File file)
025: throws ConcurrentModificationException, IOException {
026: this ();
027: setFile(file);
028: }
029:
030: public TextLineInfo(Reader reader)
031: throws ConcurrentModificationException, IOException {
032: this ();
033: setReader(reader);
034: }
035:
036: public void setFile(File file)
037: throws ConcurrentModificationException, IOException {
038: initLines(new InputStreamReader(new FileInputStream(file)));
039: }
040:
041: public void setReader(Reader reader)
042: throws ConcurrentModificationException, IOException {
043: initLines(reader);
044: }
045:
046: private void initLines(Reader reader)
047: throws ConcurrentModificationException, IOException {
048: ArrayList list = new ArrayList();
049:
050: try {
051: BufferedReader br = new BufferedReader(reader);
052: String s;
053:
054: while ((s = br.readLine()) != null) {
055: list.add(s);
056: }
057: } catch (IOException e) {
058: IOUtils.closeQuietly(reader);
059: throw e;
060: } catch (ConcurrentModificationException e) {
061: IOUtils.closeQuietly(reader);
062: throw e;
063: } finally {
064: IOUtils.closeQuietly(reader);
065: }
066:
067: int size = list.size();
068: m_lines = new int[size];
069: for (int i = 0; i < size; i++) {
070: m_lines[i] = ((String) list.get(i)).length() + 1;
071: }
072: }
073:
074: public int lineSize(int line) {
075: if (line < 0 || line > m_lines.length) {
076: return 0;
077: }
078: return m_lines[line];
079: }
080:
081: public int offset(int line) {
082: int result = 0;
083:
084: if (line == 0)
085: return 0;
086:
087: for (int i = 0; i < line; i++) {
088: result += m_lines[i];
089: }
090:
091: return result;
092: }
093:
094: public int offset(int line, int col) {
095: if (line < 0 || line > m_lines.length) {
096: return 0;
097: }
098: int result = offset(line);
099: if (col > 0) {
100: result += col;
101: }
102: return result;
103: }
104: }
|