1 52 53 package com.go.trove.io; 54 55 import java.io.*; 56 57 63 public class TagReader extends EscapeReader { 64 private int mTagCount; 65 private int[] mTagStarts; 66 private String [] mTagEnds; 67 private int[] mCodes; 68 69 private char[] mMinibuf; 70 71 private static int maxLength(String [] tags) { 72 int max = 0; 73 74 for (int i=0; i<tags.length; i++) { 75 if (tags[i].length() > max) { 76 max = tags[i].length(); 77 } 78 } 79 80 return max; 81 } 82 83 public TagReader(Reader source, String [] tags, int[] codes) { 84 super(source, maxLength(tags)); 85 86 mTagCount = tags.length; 87 mTagStarts = new int[mTagCount]; 88 mTagEnds = new String [mTagCount]; 89 mCodes = new int[mTagCount]; 90 91 for (int i=0; i<mTagCount; i++) { 92 mTagStarts[i] = tags[i].charAt(0); 93 mTagEnds[i] = tags[i].substring(1); 94 mCodes[i] = codes[i]; 95 } 96 97 mMinibuf = new char[maxLength(tags)]; 98 } 99 100 public int read() throws IOException { 101 int c = mSource.read(); 102 103 if (c == -1 || !mEscapesEnabled) { 104 return c; 105 } 106 107 for (int i=0; i<mTagCount; i++) { 108 if (mTagStarts[i] == c) { 109 int length = mTagEnds[i].length(); 110 111 mMinibuf[0] = (char)c; 112 int len = mSource.read(mMinibuf, 0, length); 113 114 if (len == length) { 115 if (new String (mMinibuf, 0, length).equals(mTagEnds[i])) { 116 return mCodes[i]; 117 } 118 } 119 120 if (len > 0) { 121 mSource.unread(len); 122 } 123 } 124 } 125 126 return c; 127 } 128 129 public static void main(String [] arg) throws Exception { 130 Tester.test(arg); 131 } 132 133 private static class Tester { 134 public static void test(String [] arg) throws Exception { 135 String str = "This <%is a %> % > > % %% >> < % test.\n"; 136 137 System.out.println("\nOriginal: " + str); 138 139 System.out.println("\nConverted:\n"); 140 141 Reader reader = new StringReader(str); 142 143 TagReader tr = new TagReader 144 (reader, new String [] {"<%", "%>"}, new int[] {-2, -3}); 145 146 PositionReader pr = new PositionReader(tr); 147 148 int c; 149 System.out.print(pr.getNextPosition() + "\t"); 150 while ( (c = pr.read()) != -1 ) { 151 System.out.println((char)c + "\t" + c); 152 System.out.print(pr.getNextPosition() + "\t"); 153 } 154 } 155 } 156 } 157 | Popular Tags |