zl程序教程

您现在的位置是:首页 >  工具

当前栏目

OutputStreamWriter 源码分析

源码 分析 OutputStreamWriter
2023-06-13 09:13:39 时间

大家好,又见面了,我是你们的朋友全栈君。 字符流通向字节流的桥梁:可使用指定的charset将要写入流中的字符编码成字节。

为了获得最高效率,可考虑将 OutputStreamWriter 包装到 BufferedWriter 中,以避免频繁调用转换器。例如:

Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

public class OutputStreamWriter extends Writer {
  
  
	// 流解码类,所有操作都交给它完成。
	private final StreamEncoder se;

	// 创建使用指定字符的OutputStreamWriter。
	public OutputStreamWriter(OutputStream out, String charsetName)
		throws UnsupportedEncodingException
	{
  
  
		super(out);
		if (charsetName == null)
			throw new NullPointerException("charsetName");
		se = StreamEncoder.forOutputStreamWriter(out, this, charsetName);
	}

	// 创建使用默认字符的OutputStreamWriter。
	public OutputStreamWriter(OutputStream out) {
  
  
		super(out);
		try {
  
  
			se = StreamEncoder.forOutputStreamWriter(out, this, (String)null);
		} catch (UnsupportedEncodingException e) {
  
  
			throw new Error(e);
		}
	}

	// 创建使用指定字符集的OutputStreamWriter。
	public OutputStreamWriter(OutputStream out, Charset cs) {
  
  
		super(out);
		if (cs == null)
			throw new NullPointerException("charset");
		se = StreamEncoder.forOutputStreamWriter(out, this, cs);
	}

	// 创建使用指定字符集编码器的OutputStreamWriter。
	public OutputStreamWriter(OutputStream out, CharsetEncoder enc) {
  
  
		super(out);
		if (enc == null)
			throw new NullPointerException("charset encoder");
		se = StreamEncoder.forOutputStreamWriter(out, this, enc);
	}

	// 返回该流使用的字符编码名。如果流已经关闭,则此方法可能返回 null。
	public String getEncoding() {
  
  
		return se.getEncoding();
	}

	// 刷新输出缓冲区到底层字节流,而不刷新字节流本身。该方法可以被PrintStream调用。
	void flushBuffer() throws IOException {
  
  
		se.flushBuffer();
	}

	// 写入单个字符
	public void write(int c) throws IOException {
  
  
		se.write(c);
	}

	// 写入字符数组的一部分
	public void write(char cbuf[], int off, int len) throws IOException {
  
  
		se.write(cbuf, off, len);
	}

	// 写入字符串的一部分
	public void write(String str, int off, int len) throws IOException {
  
  
		se.write(str, off, len);
	}

	// 刷新该流。
	public void flush() throws IOException {
  
  
		se.flush();
	}

	// 关闭该流。
	public void close() throws IOException {
  
  
		se.close();
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/194932.html原文链接:https://javaforall.cn