1 24 25 package org.aspectj.util; 26 27 import java.io.*; 28 29 public class UnicodeEscapeWriter extends Writer { 30 protected OutputStream outputStream; 31 protected byte[] buffer; 32 protected static final int bufferSize = 2048; 33 protected int index; 34 protected boolean addSlash; 35 36 public UnicodeEscapeWriter(OutputStream outputStream) { 37 this.outputStream = outputStream; 38 buffer = new byte[bufferSize+16]; 40 index = 0; 41 addSlash = false; 42 } 43 44 public void write(int ch) throws IOException { 45 if (addSlash && ch == 'u') { 46 buffer[index++] = (byte)'\\'; 47 } 49 50 if (ch == '\\') { 51 addSlash = !addSlash; 52 } else { 53 addSlash = false; 54 } 55 56 if (ch < 1 || ch > 126) { 57 int b1 = ch>>12; 58 int b2 = ch>>8 & 0xf; 59 int b3 = ch>>4 & 0xf; 60 int b4 = ch & 0xf; 61 62 buffer[index++] = (byte)'\\'; 63 buffer[index++] = (byte)'u'; 64 buffer[index++] = (byte)Character.forDigit(b1, 16); 65 buffer[index++] = (byte)Character.forDigit(b2, 16); 66 buffer[index++] = (byte)Character.forDigit(b3, 16); 67 buffer[index++] = (byte)Character.forDigit(b4, 16); 68 } else { 69 buffer[index++] = (byte)ch; 70 } 71 72 if (index >= bufferSize) flushBuffer(); 73 } 74 75 public void flushBuffer() throws IOException { 76 outputStream.write(buffer, 0, index); 77 index = 0; 78 } 79 80 public void write(char[] cbuf, int off, int len) throws IOException { 81 int index=0; 82 while (index<len) { 83 write(cbuf[off+index++]); 84 } 85 } 86 87 public void close() throws IOException { 88 flushBuffer(); 89 outputStream.close(); 90 } 91 92 public void flush() throws IOException { 93 flushBuffer(); 94 outputStream.flush(); 95 } 96 97 99 100 public static void main(String [] args) throws IOException { 101 UnicodeEscapeWriter writer = new UnicodeEscapeWriter(System.out); 102 writer.write("x = '\u0000'; y = '\u0032\u0033\u1234\uabcd'\n"); 103 writer.write("\\"+"u"+"xxxx"); 104 writer.flush(); 105 } 106 } 107 | Popular Tags |