Java-IO之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); } }
基于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(字符缓冲输出流)的更多相关文章
- BufferedWriter字符缓冲输出流和BufferedReader字符缓冲输入流
package com.yang.Test.BufferedStudy; import java.io.BufferedWriter; import java.io.FileWriter; impor ...
- java io系列24之 BufferedWriter(字符缓冲输出流)
转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_24.html 更多内容请参考:java io系列01之 "目录" Buffere ...
- Java IO流之字符缓冲流
字符流: 1.加入字符缓存流,增强读取功能(readLine) 2.更高效的读取数据 BufferedReader 从字符输入流读取文本,缓冲各个字符,从而实现字符.数组和行的高效读取. FileRe ...
- Java—转换流、字符缓冲流
转换流 OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的字符编码表,将要写入流中的字符编码成字节.它的作用的就是,将字符串按照指定的编码表转成字节,在使用字节流将这些字节写 ...
- Java IO 字节流与字符流 (三)
概述 IO流用来处理设备之间的数据传输 Java对数据的操作时通过流的方式 Java用于操作流的对象都在IO包中 流按操作的数据分为:字节流和字符流 流按流向不同分为:输入流和输出流 IO流常用基类 ...
- javaee字符缓冲输出流
package Zjshuchu; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOExcepti ...
- BufferedWniter_字符缓冲输出流和BufferedReader_字符缓冲输入流
java.io.BufferedWriter extends Writer BufferedWriter:字符缓冲输出流 继承自父类的共性成员方法: -void write(int c)写入单个字符 ...
- java io流(字符流) 文件打开、读取文件、关闭文件
java io流(字符流) 文件打开 读取文件 关闭文件 //打开文件 //读取文件内容 //关闭文件 import java.io.*; public class Index{ public sta ...
- Java IO: 字节和字符数组
原文链接 作者: Jakob Jenkov 译者:homesick 内容列表 从InputStream或者Reader中读入数组 从OutputStream或者Writer中写数组 在java中 ...
随机推荐
- Windows下使用notepad++对文本进行行列转换
行转列: Ctrl + F 选择替换 查找目标:填写指定的内容 替换为:\r\n 查找模式:正则表达式 单击替换或全部替换按钮 列转行: Ctrl + F 选择替换 查找目标:\r\n 替换为:不 ...
- 本地缓存,Redis缓存,数据库DB查询(结合代码分析)
问题背景 为什么要使用缓存?本地缓存/Redis缓存/数据库查询优先级? 一.为什么要使用缓存 原因:CPU的速度远远高于磁盘IO的速度问题:很多信息存在数据库当中的,每次查询数据库就是一次IO操作所 ...
- ⏰Day.js 2kB超轻量时间库 和Moment.js一样的API
Moment.js 是一个大而全的 JS 时间库,很大地方便了我们处理日期和时间.但是 Moment.js太重了(200k+ with locals),可能一般项目也只使用到了她几个常用的API.虽然 ...
- js去掉最后一个字符
console.log(("0,1,2,3,4,5,".slice(0,-1)))
- C# 基础问答
1.静态变量和非静态变量的区别? 2.const 和 static readonly 区别? 3.extern 是什么意思? 4.abstract 是什么意思? 5.internal 修饰符起什么作用 ...
- 剑指架构师系列-Logstash分布式系统的日志监控
Logstash主要做由三部署组成: Collect:数据输入 Enrich:数据加工,如过滤,改写等 Transport:数据输出 下面来安装一下: wget https://download.el ...
- Java为什么要配置环境变量及如何配置环境变量
在没有配置环境变量之前,用cmd执行Java文件,需要指明Java的可执行文件,否则无法运行. 配置环境是为了在不用切换可执行文件目录下,方便Java程序的执行和控制. 那么环境变量就是让系统根据环境 ...
- Python3 数据结构
列表 Python中列表是可变的,这是它区别于字符串和元组的最重要的特点,一句话概括即:列表可以修改,而字符串和元组不能. 以下是 Python 中列表的方法: 方法 描述 list.append(x ...
- Dynamics CRM2016 Web Api之分页查询
在dynamics crm web api还没出现前,我们是通过fetchxml来实现的,当然这种方式依旧可行,那既然web api来了我们就拥抱新的方式. web api中我们通过指定查询的条数来实 ...
- springMVC源码--Controller控制器
springMVC给我们提供Controller控制器,用来实现我们的逻辑处理,在Controller接口中定义的方法也是比较简单的,如下: Controller接口及实现类: