stringoutputstream.java

来自「Jodd是一个开源的公用Java基础类库」· Java 代码 · 共 82 行

JAVA
82
字号
package jodd.util;

import java.io.OutputStream;
import java.io.Serializable;

/**
 * Provides an OutputStream to an internal String. Internally converts bytes
 * to a Strings and stores them in an internal StringBuffer.
 */
public class StringOutputStream extends OutputStream implements Serializable {
	
	/**
	 * The internal destination StringBuffer.
	 */
	protected StringBuffer buf = null;

	/**
	 * Creates new StringOutputStream, makes a new internal StringBuffer.
	 */
	public StringOutputStream() {
		super();
		buf = new StringBuffer();
	}

	/**
	 * Returns the content of the internal StringBuffer as a String, the result
	 * of all writing to this OutputStream.
	 *
	 * @return returns the content of the internal StringBuffer
	 */
	public String toString() {
		return buf.toString();
	}

	/**
	* Sets the internal StringBuffer to null.
	*/
	public void close() {
		buf = null;

	}

	/**
	 * Writes and appends byte array to StringOutputStream.
	 *
	 * @param b      byte array
	 */
	public void write(byte[] b) {
		buf.append(CharUtil.toCharArray(b));
	}

	/**
	 * Writes and appends a byte array to StringOutputStream.
	 *
	 * @param b      the byte array
	 * @param off    the byte array starting index
	 * @param len    the number of bytes from byte array to write to the stream
	 */
	public void write(byte[] b, int off, int len) {
		if ((off < 0) || (len < 0) || (off + len) > b.length) {
			throw new IndexOutOfBoundsException("StringOutputStream.write: Parameters out of bounds.");
		}
		byte[] bytes = new byte[len];
		for (int i = 0; i < len; i++) {
			bytes[i] = b[off];
			off++;
		}
		buf.append(CharUtil.toCharArray(bytes));
	}

	/**
	 * Writes and appends a single byte to StringOutputStream.
	 *
	 * @param b      the byte as an int to add
	 */
	public void write(int b) {
		buf.append((char)b);
	}
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?