BufferedWriter是字符缓冲输出流,继承于Writer,作用是为其他字符输出流添加一些缓冲功能。
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的示代码:

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);
}
}
结果:
文件里写入:abcdefghij

基于JDK8的BufferedWriter的源码:

public class BufferedWriter extends Writer {

private Writer out;

    private char cb[];//缓冲字符数组
// nChars 是cb缓冲区中字符的总的个数
// nextChar 是下一个要读取的字符在cb缓冲区中的位置
private int nChars, nextChar;

    private static int defaultCharBufferSize = 8192;//默认大小是8K

/**
     * Line separator string.  This is the value of the line.separator
     * property at the moment that the stream was created.
     */
private String lineSeparator;

/**
     * Creates a buffered character-output stream that uses a default-sized
     * output buffer.
     *
     * @param  out  A Writer
     */
//构造函数
public BufferedWriter(Writer out) {
this(out, defaultCharBufferSize);
}

/**
     * Creates a new buffered character-output stream that uses an output
     * buffer of the given size.
     *
     * @param  out  A Writer
     * @param  sz   Output-buffer size, a positive integer
     *
     * @exception  IllegalArgumentException  If {@code sz <= 0}
     */
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"));
}

/** Checks to make sure that the stream has not been closed */
//检查流没有被关闭
private void ensureOpen() throws IOException {
if (out == null)
throw new IOException("Stream closed");
}

/**
     * Flushes the output buffer to the underlying character stream, without
     * flushing the stream itself.  This method is non-private only so that it
     * may be invoked by PrintStream.
     */
//刷新流,最后用本地方法写
void flushBuffer() throws IOException {
synchronized (lock) {
            ensureOpen();
            if (nextChar == 0)
return;
out.write(cb, 0, nextChar);
nextChar = 0;
}
    }

/**
     * Writes a single character.
     *
     * @exception  IOException  If an I/O error occurs
     */
//写单个字符
public void write(int c) throws IOException {
synchronized (lock) {
            ensureOpen();
            if (nextChar >= nChars)//当前字符位置大于等于字符总数时,刷新
flushBuffer();
cb[nextChar++] = (char) c;
}
    }

/**
     * Our own little min method, to avoid loading java.lang.Math if we've run
     * out of file descriptors and we're trying to print a stack trace.
     */
//获取最小值
private int min(int a, int b) {
if (a < b) return a;
        return b;
}

/**
     * Writes a portion of an array of characters.
     *
     * <p> Ordinarily this method stores characters from the given array into
     * this stream's buffer, flushing the buffer to the underlying stream as
     * needed.  If the requested length is at least as large as the buffer,
     * however, then this method will flush the buffer and write the characters
     * directly to the underlying stream.  Thus redundant
     * <code>BufferedWriter</code>s will not copy data unnecessarily.
     *
     * @param  cbuf  A character array
     * @param  off   Offset from which to start reading characters
     * @param  len   Number of characters to write
     *
     * @exception  IOException  If an I/O error occurs
     */
//写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) {//如果len已经大于nChar,不再放到缓冲区,直接写
/* 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();
}
        }
    }

/**
     * Writes a portion of a String.
     *
     * <p> If the value of the <tt>len</tt> parameter is negative then no
     * characters are written.  This is contrary to the specification of this
     * method in the {@linkplain java.io.Writer#write(java.lang.String,int,int)
     * superclass}, which requires that an {@link IndexOutOfBoundsException} be
     * thrown.
     *
     * @param  s     String to be written
     * @param  off   Offset from which to start reading characters
     * @param  len   Number of characters to be written
     *
     * @exception  IOException  If an I/O error occurs
     */
//写字符串
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();
}
        }
    }

/**
     * Writes a line separator.  The line separator string is defined by the
     * system property <tt>line.separator</tt>, and is not necessarily a single
     * newline ('\n') character.
     *
     * @exception  IOException  If an I/O error occurs
     */
public void newLine() throws IOException {
        write(lineSeparator);
}

/**
     * Flushes the stream.
     *
     * @exception  IOException  If an I/O error occurs
     */
public void flush() throws IOException {
synchronized (lock) {
            flushBuffer();
out.flush();
}
    }

@SuppressWarnings("try")
public void close() throws IOException {
synchronized (lock) {
if (out == null) {
return;
}
try (Writer w = out) {
                flushBuffer();
} finally {
out = null;
cb = null;
}
        }
    }
}

Java-IO之BufferedWriter(字符缓冲输出流)的更多相关文章

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

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

  2. java io系列24之 BufferedWriter(字符缓冲输出流)

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

  3. Java IO流之字符缓冲流

    字符流: 1.加入字符缓存流,增强读取功能(readLine) 2.更高效的读取数据 BufferedReader 从字符输入流读取文本,缓冲各个字符,从而实现字符.数组和行的高效读取. FileRe ...

  4. Java—转换流、字符缓冲流

    转换流 OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的字符编码表,将要写入流中的字符编码成字节.它的作用的就是,将字符串按照指定的编码表转成字节,在使用字节流将这些字节写 ...

  5. Java IO 字节流与字符流 (三)

    概述 IO流用来处理设备之间的数据传输 Java对数据的操作时通过流的方式 Java用于操作流的对象都在IO包中 流按操作的数据分为:字节流和字符流 流按流向不同分为:输入流和输出流 IO流常用基类 ...

  6. javaee字符缓冲输出流

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

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

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

  8. java io流(字符流) 文件打开、读取文件、关闭文件

    java io流(字符流) 文件打开 读取文件 关闭文件 //打开文件 //读取文件内容 //关闭文件 import java.io.*; public class Index{ public sta ...

  9. Java IO: 字节和字符数组

    原文链接  作者: Jakob Jenkov   译者:homesick 内容列表 从InputStream或者Reader中读入数组 从OutputStream或者Writer中写数组 在java中 ...

随机推荐

  1. 数据结构与算法 —— 链表linked list(05)

    反转一个单链表. 进阶:链表可以迭代或递归地反转.你能否两个都实现一遍? 示例 : 给定这个链表:1->2->3->4->5 返回结果: 5->4->3->2 ...

  2. java客户端Jedis操作Redis Sentinel 连接池

    pom配置: <dependency> <groupId>org.springframework.data</groupId> <artifactId> ...

  3. 前端实现搜索历史和清空历史(angularjs+ionic)

    要实现的页面效果: 1.显示历史搜索, 2.最近搜索的排在最前, 2.最多显示8条历史 4.清空历史记录 思路: 1.首先显示历史记录需要一个数组searchItems,通过ng-repeat显示每一 ...

  4. mongoose多条件模糊查询实例

    mongoose多条件模糊查询 这是今天手头项目中遇到的一个问题,关于mongoose如何实现类似于SQL中 nick LIKE '%keyword%' or email LIKE '%keyword ...

  5. 首届.NET Core开源峰会

    首届.NET Core开源峰会 代号:dnc 2018 亮点:去中心化.社区驱动 开源峰会 时间:2018年5月20日 周日 地点:在线峰会.远程参与 形式:每个主题5分钟-15分钟闪电演讲 演讲方式 ...

  6. 听说图像识别很难,大神十行代码进行Python图像识别

      随着深度学习算法的兴起和普及,人工智能领域取得了令人瞩目的进步,特别是在计算机视觉领域.21世纪的第二个十年迅速采用卷积神经网络,发明了最先进的算法,大量训练数据的可用性以及高性能和高性价比计算的 ...

  7. ACM Ignatius and the Princess II

    Problem Description Now our hero finds the door to the BEelzebub feng5166. He opens the door and fin ...

  8. Node.js 集群

    稳定性: 2 - 不稳定 单个 Node 实例运行在一个线程中.为了更好的利用多核系统的能力,可以启动 Node 集群来处理负载. 在集群模块里很容易就能创建一个共享所有服务器接口的进程. var c ...

  9. PHP echo和print 语句

    PHP  echo 和 print 语句 在 PHP 中有两个基本的输出方式: echo 和 print. 本章节中我们会详细讨论两个语句的用法,并在实例中演示如何使用 echo 和 print. P ...

  10. GDAL C#版本 "安全透明方法"问题解决方案

    之前写过一篇关于再C#中调用GDAL库出现OSGeo.GDAL.GdalPINVOKE"的类型初始值设定项引发异常的解决方案,博客地址见下: http://blog.csdn.net/lim ...