com.day.io.WriterOutputStream Maven / Gradle / Ivy
/*
* $Id: WriterOutputStream.java 12345 2004-08-22 04:56:09Z fielding $
*
* Copyright 1997-2004 Day Management AG
* Barfuesserplatz 6, 4001 Basel, Switzerland
* All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Day Management AG, ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Day.
*/
package com.day.io;
import sun.io.ByteToCharConverter;
import sun.io.MalformedInputException;
import sun.io.ConversionBufferFullException;
import java.io.OutputStream;
import java.io.Writer;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* This is a simple wrapper around a writer using a character encoding for the
* byte to character conversion.
*
* @version $Revision: 1.2 $
* @author tripod
* @since fennec
*/
public class WriterOutputStream extends OutputStream {
/** the target writer */
private Writer out;
/** the byte to character converter */
private ByteToCharConverter btc;
/**
* Creates a new WriterOutputStream
* @param writer the underlaying writer
* @param encoding the character encoding
* @throws UnsupportedEncodingException
*/
public WriterOutputStream(Writer writer, String encoding)
throws UnsupportedEncodingException {
this.out = writer;
this.btc = ByteToCharConverter.getConverter(encoding);
}
public void write(int b) throws IOException {
write(new byte[]{(byte)b}, 0 ,1);
}
public void write(byte[] b, int off, int len) throws IOException {
// could be done cooler
int estCount = btc.getMaxCharsPerByte() * len;
char[] buffer = new char[estCount];
int written = btc.convert(b, off, len+off, buffer, 0, buffer.length);
out.write(buffer, 0, written);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void flush() throws IOException {
char[] buffer = new char[8192]; // no clue?
int written = btc.flush(buffer, 0, buffer.length);
out.write(buffer, 0, written);
out.flush();
}
}