1 10 package org.mmbase.util; 11 12 import java.io.*; 13 14 28 public class EncodingDetectingOutputStreamWriter extends Writer { 29 30 private OutputStream outputStream; 31 32 private Writer wrapped = null; 34 private StringBuffer buffer = new StringBuffer (100); 35 36 EncodingDetectingOutputStreamWriter(OutputStream os) { 37 outputStream = os; 38 } 39 40 44 private void wrap() throws IOException { 45 if (wrapped == null) { 46 String encoding = GenericResponseWrapper.getXMLEncoding(buffer.toString()); 47 if (encoding == null) { 48 encoding = "UTF-8"; 49 } 50 try { 51 wrapped = new OutputStreamWriter(outputStream, encoding); 52 } catch (UnsupportedEncodingException uee) { 53 } 54 wrapped.write(buffer.toString()); 55 buffer = null; 56 } 57 } 58 public void close() throws IOException { 59 wrap(); 60 wrapped.close(); 61 } 62 public void flush() throws IOException { 63 wrap(); 64 wrapped.flush(); 65 } 66 67 public void write(char[] cbuf) throws IOException { 68 if (wrapped != null) { 69 wrapped.write(cbuf); 70 } else { 71 write(cbuf, 0, cbuf.length); 72 } 73 } 74 75 public void write(int c) throws IOException { 76 if (wrapped != null) { wrapped.write(c); } else { super.write(c); } 77 } 78 79 public void write(String str) throws IOException { 80 if (wrapped != null) { wrapped.write(str); } else { super.write(str); } 81 } 82 83 public void write(String str, int off, int len) throws IOException { 84 if (wrapped != null) { wrapped.write(str, off, len); } else { super.write(str, off, len); } 85 86 } 87 public void write(char[] cbuf, int off, int len) throws IOException { 88 if (wrapped != null) { 89 wrapped.write(cbuf, off, len); 90 } else { 91 for (int i = off; i < len + off; i++) { 92 buffer.append(cbuf[i]); 93 if (buffer.length() == 100) { 94 wrap(); 95 i++; 96 if (i < len) { 97 wrapped.write(cbuf, i, len - (i - off)); 98 } 99 break; 100 } 101 } 102 } 103 } 104 } 105 | Popular Tags |