转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_24.html

更多内容请参考:java io系列01之 "目录"

BufferedWriter 介绍

BufferedWriter 是缓冲字符输出流。它继承于Writer。
BufferedWriter 的作用是为其他字符输出流添加一些缓冲功能。

BufferedWriter 函数列表

// 构造函数
BufferedWriter(Writer out)
BufferedWriter(Writer out, int sz) void close() // 关闭此流,但要先刷新它。
void flush() // 刷新该流的缓冲。
void newLine() // 写入一个行分隔符。
void write(char[] cbuf, int off, int len) // 写入字符数组的某一部分。
void write(int c) // 写入单个字符。
void write(String s, int off, int len) // 写入字符串的某一部分。

BufferedWriter 源码分析(基于jdk1.7.40)

 package java.io;

 public class BufferedWriter extends Writer {

     // 输出流对象
private Writer out; // 保存“缓冲输出流”数据的字符数组
private char cb[]; // nChars 是cb缓冲区中字符的总的个数
// nextChar 是下一个要读取的字符在cb缓冲区中的位置
private int nChars, nextChar; // 默认字符缓冲区大小
private static int defaultCharBufferSize = 8192; // 行分割符
private String lineSeparator; // 构造函数,传入“Writer对象”,默认缓冲区大小是8k
public BufferedWriter(Writer out) {
this(out, defaultCharBufferSize);
} // 构造函数,传入“Writer对象”,指定缓冲区大小是sz
public BufferedWriter(Writer out, int sz) {
super(out);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.out = out;
cb = new char[sz];
nChars = sz;
nextChar = 0; lineSeparator = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
} // 确保“BufferedWriter”是打开状态
private void ensureOpen() throws IOException {
if (out == null)
throw new IOException("Stream closed");
} // 对缓冲区执行flush()操作,将缓冲区的数据写入到Writer中
void flushBuffer() throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar == 0)
return;
out.write(cb, 0, nextChar);
nextChar = 0;
}
} // 将c写入到缓冲区中。先将c转换为char,然后将其写入到缓冲区。
public void write(int c) throws IOException {
synchronized (lock) {
ensureOpen();
// 若缓冲区满了,则清空缓冲,将缓冲数据写入到输出流中。
if (nextChar >= nChars)
flushBuffer();
cb[nextChar++] = (char) c;
}
} // 返回a,b中较小的数
private int min(int a, int b) {
if (a < b) return a;
return b;
} // 将字符数组cbuf写入到缓冲中,从cbuf的off位置开始写入,写入长度是len。
public void write(char cbuf[], int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
} if (len >= nChars) {
/* If the request length exceeds the size of the output buffer,
flush the buffer and then write the data directly. In this
way buffered streams will cascade harmlessly. */
flushBuffer();
out.write(cbuf, off, len);
return;
} int b = off, t = off + len;
while (b < t) {
int d = min(nChars - nextChar, t - b);
System.arraycopy(cbuf, b, cb, nextChar, d);
b += d;
nextChar += d;
if (nextChar >= nChars)
flushBuffer();
}
}
} // 将字符串s写入到缓冲中,从s的off位置开始写入,写入长度是len。
public void write(String s, int off, int len) throws IOException {
synchronized (lock) {
ensureOpen(); int b = off, t = off + len;
while (b < t) {
int d = min(nChars - nextChar, t - b);
s.getChars(b, b + d, cb, nextChar);
b += d;
nextChar += d;
if (nextChar >= nChars)
flushBuffer();
}
}
} // 将换行符写入到缓冲中
public void newLine() throws IOException {
write(lineSeparator);
} // 清空缓冲区数据
public void flush() throws IOException {
synchronized (lock) {
flushBuffer();
out.flush();
}
} public void close() throws IOException {
synchronized (lock) {
if (out == null) {
return;
}
try {
flushBuffer();
} finally {
out.close();
out = null;
cb = null;
}
}
}
}

说明: BufferedWriter的源码非常简单,这里就BufferedWriter的思想进行简单说明:BufferedWriter通过字符数组来缓冲数据,当缓冲区满或者用户调用flush()函数时,它就会将缓冲区的数据写入到输出流中。

示例代码

关于BufferedWriter中API的详细用法,参考示例代码(BufferedWriterTest.java):

 import java.io.BufferedWriter;
import java.io.File;
import java.io.OutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Scanner; /**
* BufferedWriter 测试程序
*
* @author skywang
*/
public class BufferedWriterTest { private static final int LEN = 5;
// 对应英文字母“abcdefghijklmnopqrstuvwxyz”
//private static final char[] ArrayLetters = "abcdefghijklmnopqrstuvwxyz";
private static final char[] ArrayLetters = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; public static void main(String[] args) {
testBufferedWriter() ;
} /**
* BufferedWriter的API测试函数
*/
private static void testBufferedWriter() { // 创建“文件输出流”对应的BufferedWriter
// 它对应缓冲区的大小是16,即缓冲区的数据>=16时,会自动将缓冲区的内容写入到输出流。
try {
File file = new File("bufferwriter.txt");
BufferedWriter out =
new BufferedWriter(
new FileWriter(file)); // 将ArrayLetters数组的前10个字符写入到输出流中
out.write(ArrayLetters, 0, 10);
// 将“换行符\n”写入到输出流中
out.write('\n'); out.flush();
//readUserInput() ; out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 读取用户输入
*/
private static void readUserInput() {
System.out.println("please input a text:");
Scanner reader=new Scanner(System.in);
// 等待一个输入
String str = reader.next();
System.out.printf("the input is : %s\n", str);
}
}

运行结果
生成文件“bufferwriter.txt”,文件的内容是“abcdefghij”。

java io系列24之 BufferedWriter(字符缓冲输出流)的更多相关文章

  1. java io系列23之 BufferedReader(字符缓冲输入流)

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_23.html 更多内容请参考:java io系列01之 "目录" Buffere ...

  2. java io系列25之 PrintWriter (字符打印输出流)

    更多内容请参考:java io系列01之 "目录" PrintWriter 介绍 PrintWriter 是字符类型的打印输出流,它继承于Writer.PrintStream 用于 ...

  3. java io系列19之 CharArrayWriter(字符数组输出流)

    本章,我们学习CharArrayWriter.学习时,我们先对CharArrayWriter有个大致了解,然后深入了解一下它的源码,最后通过示例来掌握它的用法. 转载请注明出处:http://www. ...

  4. BufferedWriter字符缓冲输出流和BufferedReader字符缓冲输入流

    package com.yang.Test.BufferedStudy; import java.io.BufferedWriter; import java.io.FileWriter; impor ...

  5. java io系列18之 CharArrayReader(字符数组输入流)

    从本章开始,我们开始对java io中的“字符流”进行学习.首先,要学习的是CharArrayReader.学习时,我们先对CharArrayReader有个大致了解,然后深入了解一下它的源码,最后通 ...

  6. java io系列01之 "目录"

    java io 系列目录如下: 01. java io系列01之  "目录" 02. java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括 ...

  7. java io系列

    java io系列01之 "目录" java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream) java io系列03之 ...

  8. javaee字符缓冲输出流

    package Zjshuchu; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOExcepti ...

  9. BufferedWniter_字符缓冲输出流和BufferedReader_字符缓冲输入流

    java.io.BufferedWriter extends Writer BufferedWriter:字符缓冲输出流 继承自父类的共性成员方法: -void write(int c)写入单个字符 ...

随机推荐

  1. kubernetes 构架

  2. 在 Activity 中实现 getContentView 操作

    2017/9/8 17:17:03   前言     最近接到个需要优化Android原生系统设置APK的任务.这个任务里面有一个更换应用背景图片的需求.我手里的这个设备是一个平板设备,使用了一下这个 ...

  3. [Codeforces741D]Arpa's letter-marked tree and Mehrdad's Dokhtar-kosh paths——dsu on tree

    题目链接: Codeforces741D 题目大意:给出一棵树,根为$1$,每条边有一个$a-v$的小写字母,求每个点子树中的一条最长的简单路径使得这条路径上的边上的字母重排后是一个回文串. 显然如果 ...

  4. ExaWizards 2019

    AB:div 3 AB??? C:div 1 C???场内自闭的直接去看D.事实上是个傻逼题,注意到物品相对顺序不变,二分边界即可. #include<iostream> #include ...

  5. BZOJ4818 [SDOI2017] 序列计数 【矩阵快速幂】

    题目分析: 一个很显然的同类项合并.注意到p的大小最大为100,考虑把模p意义下相同的求出来最后所有的减去没有质数的做矩阵快速幂即可. 代码: #include<bits/stdc++.h> ...

  6. 爬虫_古诗文网(队列,多线程,锁,正则,xpath)

      import requests from queue import Queue import threading from lxml import etree import re import c ...

  7. 【 HDU4773 】Problem of Apollonius (圆的反演)

    BUPT2017 wintertraining(15) #5G HDU - 4773 - 2013 Asia Hangzhou Regional Contest problem D 题意 给定两个相离 ...

  8. 【Luogu4707】重返现世(min-max容斥)

    [Luogu4707]重返现世(min-max容斥) 题面 洛谷 求全集的\(k-max\)的期望 题解 \(min-max\)容斥的证明不难,只需要把所有元素排序之后考虑组合数的贡献,容斥系数先设出 ...

  9. urllib的实现---请求响应and请求头处理

    在python3中 urllib库和urilib2库合并成了urllib库..其中urllib2.urlopen()变成了urllib.request.urlopen()urllib2.Request ...

  10. Tbox在整车CAN网络的位置与作用

    我们讲到了智能车载娱乐系统的5个基本特征: 基本来说, 当今的智能车机基本有以下几个特点: 基于智能操作系统: Android, Yunos, Linux等 基本都是虚拟按键, 较少用实体按键 具备外 ...