Java-IO之字符输入输出流(Reader和Writer)
以字符为单位的输入流的公共父类是Reader:
以字符为单位的输出流的超类是Writer:
基于JDK8的Reader的源码:
public abstract class Reader implements Readable, Closeable {
/**
* The object used to synchronize operations on this stream. For
* efficiency, a character-stream object may use an object other than
* itself to protect critical sections. A subclass should therefore use
* the object in this field rather than <tt>this</tt> or a synchronized
* method.
*/
protected Object lock;
/**
* Creates a new character-stream reader whose critical sections will
* synchronize on the reader itself.
*/
protected Reader() {
this.lock = this;
}
/**
* Creates a new character-stream reader whose critical sections will
* synchronize on the given object.
*
* @param lock The Object to synchronize on.
*/
protected Reader(Object lock) {
if (lock == null) {
throw new NullPointerException();
}
this.lock = lock;
}
//尝试读字符进字符缓冲
public int read(java.nio.CharBuffer target) throws IOException {
int len = target.remaining();
char[] cbuf = new char[len];
int n = read(cbuf, 0, len);
if (n > 0)
target.put(cbuf, 0, n);
return n;
}
//读单个字符,方法会阻塞直到字符是有效,出现IO错误,或者流完毕
public int read() throws IOException {
char cb[] = new char[1];
if (read(cb, 0, 1) == -1)
return -1;
else
return cb[0];
}
//读字符数组
public int read(char cbuf[]) throws IOException {
return read(cbuf, 0, cbuf.length);
}
abstract public int read(char cbuf[], int off, int len) throws IOException;
/** Maximum skip-buffer size */
private static final int maxSkipBufferSize = 8192;
/** Skip buffer, null until allocated */
private char skipBuffer[] = null;
/**
* Skips characters. This method will block until some characters are
* available, an I/O error occurs, or the end of the stream is reached.
*
* @param n The number of characters to skip
*
* @return The number of characters actually skipped
*
* @exception IllegalArgumentException If <code>n</code> is negative.
* @exception IOException If an I/O error occurs
*/
public long skip(long n) throws IOException {
if (n < 0L)
throw new IllegalArgumentException("skip value is negative");
int nn = (int) Math.min(n, maxSkipBufferSize);
synchronized (lock) {
if ((skipBuffer == null) || (skipBuffer.length < nn))
skipBuffer = new char[nn];
long r = n;
while (r > 0) {
int nc = read(skipBuffer, 0, (int)Math.min(r, nn));
if (nc == -1)
break;
r -= nc;
}
return n - r;
}
}
/**
* Tells whether this stream is ready to be read.
*
*/
//是否准备好去读
public boolean ready() throws IOException {
return false;
}
//不支持标记
public boolean markSupported() {
return false;
}
//会抛出错误
public void mark(int readAheadLimit) throws IOException {
throw new IOException("mark() not supported");
}
//不支持reset,会抛出错误
public void reset() throws IOException {
throw new IOException("reset() not supported");
}
//关闭资源
abstract public void close() throws IOException;
}
基于JDK8的Writer源码:
public abstract class Writer implements Appendable, Closeable, Flushable {
/**
* Temporary buffer used to hold writes of strings and single characters
*/
//写缓冲数组
private char[] writeBuffer;
/**
* Size of writeBuffer, must be >= 1
*/
//写缓冲数组默认大小是1024
private static final int WRITE_BUFFER_SIZE = 1024;
/**
* The object used to synchronize operations on this stream. For
* efficiency, a character-stream object may use an object other than
* itself to protect critical sections. A subclass should therefore use
* the object in this field rather than <tt>this</tt> or a synchronized
* method.
*/
//对象
protected Object lock;
/**
* Creates a new character-stream writer whose critical sections will
* synchronize on the writer itself.
*/
//
protected Writer() {
this.lock = this;
}
/**
* Creates a new character-stream writer whose critical sections will
* synchronize on the given object.
*
* @param lock
* Object to synchronize on
*/
protected Writer(Object lock) {
if (lock == null) {
throw new NullPointerException();
}
this.lock = lock;
}
/**
* Writes a single character. The character to be written is contained in
* the 16 low-order bits of the given integer value; the 16 high-order bits
* are ignored.
*
* <p> Subclasses that intend to support efficient single-character output
* should override this method.
*
* @param c
* int specifying a character to be written
*
* @throws IOException
* If an I/O error occurs
*/
//写一个字符
public void write(int c) throws IOException {
synchronized (lock) {
if (writeBuffer == null){
writeBuffer = new char[WRITE_BUFFER_SIZE];
}
writeBuffer[0] = (char) c;
write(writeBuffer, 0, 1);
}
}
/**
* Writes an array of characters.
*
* @param cbuf
* Array of characters to be written
*
* @throws IOException
* If an I/O error occurs
*/
//写一个字符数组
public void write(char cbuf[]) throws IOException {
write(cbuf, 0, cbuf.length);
}
abstract public void write(char cbuf[], int off, int len) throws IOException;
//写一个String
public void write(String str) throws IOException {
write(str, 0, str.length());
}
//写一个字符串的一部分
public void write(String str, int off, int len) throws IOException {
synchronized (lock) {
char cbuf[];
if (len <= WRITE_BUFFER_SIZE) {
if (writeBuffer == null) {
writeBuffer = new char[WRITE_BUFFER_SIZE];
}
cbuf = writeBuffer;
} else { // Don't permanently allocate very large buffers.
cbuf = new char[len];
}
str.getChars(off, (off + len), cbuf, 0);
write(cbuf, 0, len);
}
}
//追加
public Writer append(CharSequence csq) throws IOException {
if (csq == null)
write("null");
else
write(csq.toString());
return this;
}
/**
* Appends a subsequence of the specified character sequence to this writer.
* <tt>Appendable</tt>.
*
* <p> An invocation of this method of the form <tt>out.append(csq, start,
* end)</tt> when <tt>csq</tt> is not <tt>null</tt> behaves in exactly the
* same way as the invocation
*
* <pre>
* out.write(csq.subSequence(start, end).toString()) </pre>
*
* @param csq
* The character sequence from which a subsequence will be
* appended. If <tt>csq</tt> is <tt>null</tt>, then characters
* will be appended as if <tt>csq</tt> contained the four
* characters <tt>"null"</tt>.
*
* @param start
* The index of the first character in the subsequence
*
* @param end
* The index of the character following the last character in the
* subsequence
*
* @return This writer
*
* @throws IndexOutOfBoundsException
* If <tt>start</tt> or <tt>end</tt> are negative, <tt>start</tt>
* is greater than <tt>end</tt>, or <tt>end</tt> is greater than
* <tt>csq.length()</tt>
*
* @throws IOException
* If an I/O error occurs
*
* @since 1.5
*/
public Writer append(CharSequence csq, int start, int end) throws IOException {
CharSequence cs = (csq == null ? "null" : csq);
write(cs.subSequence(start, end).toString());
return this;
}
/**
* Appends the specified character to this writer.
*
* <p> An invocation of this method of the form <tt>out.append(c)</tt>
* behaves in exactly the same way as the invocation
*
* <pre>
* out.write(c) </pre>
*
* @param c
* The 16-bit character to append
*
* @return This writer
*
* @throws IOException
* If an I/O error occurs
*
* @since 1.5
*/
public Writer append(char c) throws IOException {
write(c);
return this;
}
/**
* Flushes the stream. If the stream has saved any characters from the
* various write() methods in a buffer, write them immediately to their
* intended destination. Then, if that destination is another character or
* byte stream, flush it. Thus one flush() invocation will flush all the
* buffers in a chain of Writers and OutputStreams.
*
* <p> If the intended destination of this stream is an abstraction provided
* by the underlying operating system, for example a file, then flushing the
* stream guarantees only that bytes previously written to the stream are
* passed to the operating system for writing; it does not guarantee that
* they are actually written to a physical device such as a disk drive.
*
* @throws IOException
* If an I/O error occurs
*/
abstract public void flush() throws IOException;
/**
* Closes the stream, flushing it first. Once the stream has been closed,
* further write() or flush() invocations will cause an IOException to be
* thrown. Closing a previously closed stream has no effect.
*
* @throws IOException
* If an I/O error occurs
*/
abstract public void close() throws IOException;
}
Java-IO之字符输入输出流(Reader和Writer)的更多相关文章
- 系统学习 Java IO (十三)----字符读写 Reader/Writer 及其常用子类
目录:系统学习 Java IO---- 目录,概览 Reader Reader 类是 Java IO API 中所有 Reader 子类的基类. Reader 类似于 InputStream ,除了它 ...
- Java IO学习--输入输出流
一.Java IO的定义 I/O:输入输出系统,由输入输出控制系统和外围设备两部分组成. Java中I/O操作主要是指使用Java进行输入,输出操作. Java所有的I/O机制都是基于数据流进行输入输 ...
- Java IO 输入和输出流
数据流是指一组有顺序的,有起点和终点的字节集合. 最初的版本中,java.io 包中的流只有普通的字节流,即以 byte 为基本处理单位的流.字节流用来读写 8 位的数据,由于不会对数据做任何转换,因 ...
- Java I/O(三)各种Reader和Writer读写器、RandomAccessFile随机访问文件、序列化
2019 01/01 八.Reader和Writer读写器 前面讲的输入输出流的基本单位都是字节,因此可以称为“字节流”,读写器是以字符为基本单位,可以称为“字符流”.它们的使用方法非常相似,因此我考 ...
- IO流 -字符输入输出流,以及异常处理方法
字符输入流 java.io.Reader: 字符输入流的顶层抽象父类 共性的成员方法: int read() 读取单个字符,并返回. int read(char[] cbuf) 将字符读入数组. ab ...
- java Io文件输入输出流 复制文件
package com.hp.io; import java.io.FileInputStream; import java.io.FileNotFoundException; import java ...
- JAVA Io 缓冲输入输出流
java中提供带缓冲的输入输出流.在打开文件进行写入或读取操作时,都会加上缓冲,提高了IO读写性能. 1. BufferedInputStream 缓冲输入流 2. BufferedOutputStr ...
- 《三》Java IO 字节输入输出流
那么这篇博客我们讲的是字节输入输出流:InputStream.OutputSteam(下图红色长方形框内),红色椭圆框内是其典型实现(FileInputSteam.FileOutStream) ...
- Java IO流-标准输入输出流
2017-11-05 19:13:21 标准输入输出流:System类中的两个成员变量. 标准输入流(public static final InputStream in):“标准”输入流.此流已打开 ...
- java.io包详细解说
转自:http://hzxdark.iteye.com/blog/40133 hzxdark的博客 我不知道各位是师弟师妹们学java时是怎样的,就我的刚学java时的感觉,java.io包是最让我感 ...
随机推荐
- 我在 B 站学机器学习(Machine Learning)- 吴恩达(Andrew Ng)【中英双语】
我在 B 站学机器学习(Machine Learning)- 吴恩达(Andrew Ng)[中英双语] 视频地址:https://www.bilibili.com/video/av9912938/ t ...
- PowerBI 第九篇:修改查询
在PowerBI的查询编辑器中,用户可以使用M语言修改Query,或修改Query字段的类型,或向Query中添加数据列(Column),对Query进行修改会导致PowerBI相应地更新数据模型(D ...
- Linux学习之CentOS(七)---常用基本操命令1
cd pwd mkdir rmdir ls cp rm mv cat tac nl more less head tail touch ①目录管理:ls.cd. ...
- 9.QT-标准对话框
Qt提供的可复用的标准对话框,全部继承自QDialog类,如下图所示: QMessageBox:信息对话框,用于显示信息.询问问题等: QFileDialog:文件对话框 QColorDialog:颜 ...
- localeCompare() 方法实现中文的拼音排序
google了很多次才发现在国外网站上有提示如何比较中文,原文地址:http://www.webdeveloper.com/forum/showthread.php?t=9365 前提:使用Unico ...
- java怎样获取CPU占用率和硬盘占用率
通过jmx可以监控vm内存使用,系统内存使用等,以下是网上某博客代码,特点是通过window和linux命令获得CPU使用率. 利用java程序实现获取计算机cpu利用率和内存使用信息. packag ...
- EF实体的部分更新
实现实体的部分更新假设实体InfoHotel如下: public class InfoHotel { public int Id{get;set;} public string Name{get;se ...
- 【转】动态规划DP
[数据结构与算法] DP 动态规划 介绍 原创 2017年02月13日 00:42:51 最近在看算法导论. DP全称是dynamic programming,这里programming不是编程,是一 ...
- Thread 调用方法的方式
1.传统ThreadStart 2.ParameterizedThreadStart 3.委托thread = new Thread(delegate() { NoticeBroadcast(user ...
- FJUT寒假作业第二周C题解(位运算)
题目来源:http://210.34.193.66:8080/vj/Contest.jsp?cid=161#P2 题意比较好理解.如果直接按题目要求一步一解.一定超时.作为一个懒人也不会这么暴力一个肯 ...