准备写一系列Java基础文章,先拿Java.io下手,今天聊一聊BufferedReader和BufferedWriter

BufferedReader

BufferedReader继承Writer,本身的方法非常简单,其官方解释如下:

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

简单翻译一下:

从流里面读取文本,通过缓存的方式提高效率,读取的内容包括字符、数组和行。

缓存的大小可以指定,也可以用默认的大小。大部分情况下,默认大小就够了。

1. 构造函数

BufferedReader有两个构造函数,其声明如下:

BufferedReader(Reader in)
Creates a buffering character-input stream that uses a default-sized input buffer.
BufferedReader(Reader in, int sz)
Creates a buffering character-input stream that uses an input buffer of the specified size.

一个是传一个Reader,另外一个增加了缓存的大小。

其真正的实现也很简单,反编译Java源码如下:

  public BufferedWriter(Writer paramWriter)
{
this(paramWriter, defaultCharBufferSize);
} public BufferedWriter(Writer paramWriter, int paramInt)
{
super(paramWriter);
if (paramInt <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
this.out = paramWriter;
this.cb = new char[paramInt];
this.nChars = paramInt;
this.nextChar = 0;
this.lineSeparator = ((String)AccessController.doPrivileged(new GetPropertyAction("line.separator")));
}

常见的初始化方法

BufferedReader br = new BufferedReader(new FileReader("d:/123.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

第一个方法是读取一个文件;第二个方法是从标准输入读。

2. 主要方法
void	close()
Closes the stream and releases any system resources associated with it.
void mark(int readAheadLimit)
Marks the present position in the stream.
boolean markSupported()
Tells whether this stream supports the mark() operation, which it does.
int read()
Reads a single character.
int read(char[] cbuf, int off, int len)
Reads characters into a portion of an array.
String readLine()
Reads a line of text.
boolean ready()
Tells whether this stream is ready to be read.
void reset()
Resets the stream to the most recent mark.
long skip(long n)
Skips characters.

提供了三种读数据的方法read、read(char[] cbuf, int off, int len)、readLine(),其中常用的是readLine。

a. read方法

Reads a single character.

这个方法从reader里面读一个字符,并向下移一位。如果读完了,会返回-1.

	public void readTest() {
try {
BufferedReader br = new BufferedReader(new FileReader("d:/123.txt"));
for (;;) {
int i = br.read();
if (i == -1) {
break;
}
System.out.print((char) i);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
b. read(char[] cbuf, int off, int len)方法
	public void readCharTest() {
try {
BufferedReader br = new BufferedReader(new FileReader("d:/123.txt"));
char[] buf = new char[100];
br.read(buf);
System.out.print(String.valueOf(buf));
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

如上,先定义一个数组,然后读进数组就可以了。如果数组比内容少,则数组满了就不读了。当然,也可以指定数据的off和len,但一般不用。

c. readline方法
	public void readline() {
try {
BufferedReader br = new BufferedReader(new FileReader("d:/123.txt"));
while (true) {
String str = br.readLine();
if (str == null) {
break;
}
System.out.println(str);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

用null判断是否读完。

d. close方法

Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

用完流之后,一定要close掉。当然,放在finally里面更保险。

3. 其他

BufferedReader的子类包括FileReader, InputStreamReader。因此,这两个子类也有如上方法。

BufferedWriter

BufferedWriter继承自java.io.Writer。

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.

1. 构造函数
BufferedWriter(Writer out)
Creates a buffered character-output stream that uses a default-sized output buffer.
BufferedWriter(Writer out, int sz)
Creates a new buffered character-output stream that uses an output buffer of the given size.

其源码如下:

  public BufferedWriter(Writer paramWriter)
{
this(paramWriter, defaultCharBufferSize);
} public BufferedWriter(Writer paramWriter, int paramInt)
{
super(paramWriter);
if (paramInt <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
this.out = paramWriter;
this.cb = new char[paramInt];
this.nChars = paramInt;
this.nextChar = 0;
this.lineSeparator = ((String)AccessController.doPrivileged(new GetPropertyAction("line.separator")));
}

用法

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedWriter bw = new BufferedWriter(new FileWriter("d:/1234.txt", true));

输出到标准输出或者输出到一个文件。

2. 主要方法
void	close()
Closes the stream, flushing it first.
void flush()
Flushes the stream.
void newLine()
Writes a line separator.
void write(char[] cbuf, int off, int len)
Writes a portion of an array of characters.
void write(int c)
Writes a single character.
void write(String s, int off, int len)
Writes a portion of a String.

既然是writer,那主要是写数据。

a. write方法
	private void writeTest() {
try {
BufferedWriter bw = new BufferedWriter(
new FileWriter("d:/1234.txt"));
bw.write("writeTest");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

注意,BufferedWriter没有write(String s)或者write(char[] s)的定义,为什么还能直接bw.write("writeTest")呢。因为BufferedWriter的父类Writer实现了这个方法。不过,writer实际上也是调用了BufferedWriter的方法实现的。

  public void write(String paramString, int paramInt1, int paramInt2)
throws IOException
{
synchronized (this.lock)
{
char[] arrayOfChar;
if (paramInt2 <= 1024)
{
if (this.writeBuffer == null) {
this.writeBuffer = new char['?'];
}
arrayOfChar = this.writeBuffer;
}
else
{
arrayOfChar = new char[paramInt2];
}
paramString.getChars(paramInt1, paramInt1 + paramInt2, arrayOfChar, 0);
write(arrayOfChar, 0, paramInt2);
}
}

其中write(arrayOfChar, 0, paramInt2)在Writer中是抽象方法,定义如下:

  public abstract void write(char[] paramArrayOfChar, int paramInt1, int paramInt2)
throws IOException;

这个是标准的模板模式啊。

b. newLine方法

newLine方法实现了换行,其源码如下:

  public void newLine()
throws IOException
{
write(this.lineSeparator);
}

代码很简单,只是写了一个换行符,那么换行符是什么呢?

this.lineSeparator = ((String)AccessController.doPrivileged(new GetPropertyAction("line.separator")));

不过,也有人说换行符有的时候不靠谱,不过我没遇到过。

在Java7之后,也可以这么写,当然,实际上是一样的。

System.lineSeparator()
c. flush方法

flush方法的说明是这样的

Flushes the stream.

也就是说会把内容flush进去,冲进去。

那什么时候用这个呢?答案就是,基本上不用。

先看看flush干了什么事情。

  public void flush()
throws IOException
{
synchronized (this.lock)
{
flushBuffer();
this.out.flush();
}
}

就是调用了flushBuffer()方法。

那么close的时候干了什么事情呢?

  public void close()
throws IOException
{
synchronized (this.lock)
{
if (this.out == null) {
return;
}
try
{
flushBuffer();
}
finally
{
this.out.close();
this.out = null;
this.cb = null;
}
}
}

注意,也调用了flushBuffer()。也就是说,只要你close了,就不用flush了。

而且,write也会flush,其代码如下:

  public void write(int paramInt)
throws IOException
{
synchronized (this.lock)
{
ensureOpen();
if (this.nextChar >= this.nChars) {
flushBuffer();
}
this.cb[(this.nextChar++)] = ((char)paramInt);
}
}

那close和write都flush了,flush还有啥用呢?有人这么说:

In other words, relax - just write, write, write and close

通过源码学Java基础:BufferedReader和BufferedWriter的更多相关文章

  1. 通过源码学Java基础:InputStream、OutputStream、FileInputStream和FileOutputStream

    1. InputStream 1.1 说明 InputStream是一个抽象类,具体来讲: This abstract class is the superclass of all classes r ...

  2. 通过源码分析Java开源任务调度框架Quartz的主要流程

    通过源码分析Java开源任务调度框架Quartz的主要流程 从使用效果.调用链路跟踪.E-R图.循环调度逻辑几个方面分析Quartz. github项目地址: https://github.com/t ...

  3. 通过源码浅析Java中的资源加载

    前提 最近在做一个基础组件项目刚好需要用到JDK中的资源加载,这里说到的资源包括类文件和其他静态资源,刚好需要重新补充一下类加载器和资源加载的相关知识,整理成一篇文章. 理解类的工作原理 这一节主要分 ...

  4. 通过源码了解Java的自动装箱拆箱

    什么叫装箱 & 拆箱? 将int基本类型转换为Integer包装类型的过程叫做装箱,反之叫拆箱. 首先看一段代码 public static void main(String[] args) ...

  5. 通过源码安装PostgresSQL

    通过源码安装PostgresSQL 1.1 下载源码包环境: Centos6.8 64位 yum -y install bison flex readline-devel zlib-devel yum ...

  6. 通过源码了解ASP.NET MVC 几种Filter的执行过程

    一.前言 之前也阅读过MVC的源码,并了解过各个模块的运行原理和执行过程,但都没有形成文章(所以也忘得特别快),总感觉分析源码是大神的工作,而且很多人觉得平时根本不需要知道这些,会用就行了.其实阅读源 ...

  7. Linux下通过源码编译安装程序

    本文简单的记录了下,在linux下如何通过源码安装程序,以及相关的知识.(大神勿喷^_^) 一.程序的组成部分 Linux下程序大都是由以下几部分组成: 二进制文件:也就是可以运行的程序文件 库文件: ...

  8. 通过源码了解ASP.NET MVC 几种Filter的执行过程 在Winform中菜单动态添加“最近使用文件”

    通过源码了解ASP.NET MVC 几种Filter的执行过程   一.前言 之前也阅读过MVC的源码,并了解过各个模块的运行原理和执行过程,但都没有形成文章(所以也忘得特别快),总感觉分析源码是大神 ...

  9. 在centos6.7通过源码安装python3.6.7报错“zipimport.ZipImportError: can't decompress data; zlib not available”

    在centos6.7通过源码安装python3.6.7报错: zipimport.ZipImportError: can't decompress data; zlib not available 从 ...

随机推荐

  1. [HDOJ2586]How far away?(最近公共祖先, 离线tarjan, 并查集)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2586 这题以前做过…现在用tarjan搞一发…竟然比以前暴力过的慢………… 由于是离线算法,需要Que ...

  2. C++STL之map的基本操作

    STL中基本的关联式容器有map和set,它们都是以红黑树作为其底层的结构,具有非常高的查找.删除效率,内容会按照键值自动排序. 使用map的注意事项: 1.关联式容器的键值是不允许修改的,所以永远不 ...

  3. sdut 2846 Remove Trees (二分 + 贪心)

    题目 和poj 上的一道题几乎一样. 题意:已知n棵树距第一棵树的距离,求删掉m棵树后的 树之间 的最小距离  的最大值. 思路:二分枚举最小的距离,注意二分的写法. #include <ios ...

  4. ArrayList和List之间的转换

    开发中不免碰到List与数组类型之间的相互转换,举一个简单的例子: package test.test1; import java.util.ArrayList; import java.util.L ...

  5. 亲测!Jquery2.0不支持IE8-了

    最近由于测试需要,Win7回退到了官方更新的IE8浏览器,惊人的发现: <script src="//cdn.bootcss.com/jquery/2.0.0/jquery.min.j ...

  6. UVa 1647 (递推) Computer Transformation

    题意: 有一个01串,每一步都会将所有的0变为10,将所有的1变为01,串最开始为1. 求第n步之后,00的个数 分析: 刚开始想的时候还是比较乱的,我还纠结了一下000中算是有1个00还是2个00 ...

  7. UVa 12096 The SetStack Computer【STL】

    题意:给出一个空的栈,支持集合的操作,求每次操作后,栈顶集合的元素个数 从紫书给的例子 A={{},{{}}} B={{},{{{}}}} A是栈顶元素,A是一个集合,同时作为一个集合的A,它自身里面 ...

  8. cocos2d-x 2.1.2 bug发现

    1.在做屏蔽触摸时发现 extensions中的CCScrollView类 void CCScrollView::registerWithTouchDispatcher() { CCDirector: ...

  9. 转载RabbitMQ入门(1)--介绍

    目录[-] "Hello World" (使用java客户端) 发送 接收 把所有放在一起 前面声明本文都是RabbitMQ的官方指南翻译过来的,由于本人水平有限难免有翻译不当的地 ...

  10. Linux下通过ioctl系统调用来获取和设置网络信息

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h&g ...