1 28 29 package com.caucho.vfs; 30 31 import com.caucho.util.CharBuffer; 32 33 import java.io.CharConversionException ; 34 import java.io.EOFException ; 35 import java.io.IOException ; 36 import java.io.UnsupportedEncodingException ; 37 38 public class StringWriter extends StreamImpl { 39 private WriteStream ws; 40 private CharBuffer cb; 41 42 public StringWriter() 43 { 44 } 45 46 public StringWriter(CharBuffer cb) 47 { 48 this.cb = cb; 49 } 50 51 54 public WriteStream openWrite() 55 { 56 if (cb != null) 57 cb.clear(); 58 else 59 cb = CharBuffer.allocate(); 60 61 if (ws == null) 62 ws = new WriteStream(this); 63 else 64 ws.init(this); 65 66 try { 67 ws.setEncoding("utf-8"); 68 } catch (UnsupportedEncodingException e) { 69 } 70 71 return ws; 72 } 73 74 public String getString() 75 { 76 try { 77 ws.close(); 78 } catch (IOException e) { 79 } 80 81 String str = cb.close(); 82 83 cb = null; 84 85 return str; 86 } 87 88 91 public boolean canWrite() 92 { 93 return true; 94 } 95 96 104 public void write(byte []buf, int offset, int length, boolean isEnd) 105 throws IOException 106 { 107 int end = offset + length; 108 while (offset < end) { 109 int ch1 = buf[offset++] & 0xff; 110 111 if (ch1 < 0x80) 112 cb.append((char) ch1); 113 else if ((ch1 & 0xe0) == 0xc0) { 114 if (offset >= end) 115 throw new EOFException ("unexpected end of file in utf8 character"); 116 117 int ch2 = buf[offset++] & 0xff; 118 if ((ch2 & 0xc0) != 0x80) 119 throw new CharConversionException ("illegal utf8 encoding"); 120 121 cb.append((char) (((ch1 & 0x1f) << 6) + (ch2 & 0x3f))); 122 } 123 else if ((ch1 & 0xf0) == 0xe0) { 124 if (offset + 1 >= end) 125 throw new EOFException ("unexpected end of file in utf8 character"); 126 127 int ch2 = buf[offset++] & 0xff; 128 int ch3 = buf[offset++] & 0xff; 129 130 if ((ch2 & 0xc0) != 0x80) 131 throw new CharConversionException ("illegal utf8 encoding"); 132 133 if ((ch3 & 0xc0) != 0x80) 134 throw new CharConversionException ("illegal utf8 encoding"); 135 136 cb.append((char) (((ch1 & 0x1f) << 12) + ((ch2 & 0x3f) << 6) + (ch3 & 0x3f))); 137 } 138 else 139 throw new CharConversionException ("illegal utf8 encoding at (" + 140 (int) ch1 + ")"); 141 } 142 } 143 } 144 | Popular Tags |