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中 ...
随机推荐
- spring+hibernate+struts2零配置整合
说句实话,很久都没使用SSH开发项目了,但是出于各种原因,再次记录一下整合方式,纯注解零配置. 一.前期准备工作 gradle配置文件: group 'com.bdqn.lyrk.ssh.study' ...
- SpringCloud学习之Ribbon
一.负载均衡与Ribbon 负载均衡,在集群中是很常见的一个“名词”,顾名思义是根据一定的算法将请求分摊至对应的服务节点上,常见的算法有如下几种: 轮询法:所有请求被依次分发到每台应用服务器上,每台服 ...
- flask的自带logger和celery的自带logger的使用
在celery和flask框架中都有自带的logger使用方法.下面记录一下相关的使用. flask中使用logger flask中的app对象FLASK()自带了logger方法,其调用的方式为: ...
- c# error
部署iis c# 连sqlserver 用IIS发布之后,网页出错.提示为:异常详细信息: System.Data.SqlClient.SqlException: 用户 'NT AUTHORITY\I ...
- 四柱加强版汉诺塔HanoiTower----是甜蜜还是烦恼
我想很多人第一次学习递归的时候,老师或者书本上可能会举汉诺塔的例子. 但是今天,我们讨论的重点不是简单的汉诺塔算法,而是三柱汉诺塔的延伸.先来看看经典的三柱汉诺塔. 一.三柱汉诺塔(Hanoi_Thr ...
- numpy.squeeze()是干啥的
例子: a = 3 print np.squeeze(a) # 输出3 a = [3] print np.squeeze(a) # 输出3 a = [[3]] print np.squeeze(a) ...
- mysql 索引列为Null的走不走索引及null在统计时的问题
要尽可能地把字段定义为 NOT NULL,即使应用程序无须保存 NULL(没有值),也有许多表包含了可空列(Nullable Column)这仅仅是因为它为默认选项.除非真的要保存 NULL,否则就把 ...
- 修改apache默认主页,重定向404页面
yum 下载apache后默认主页 默认配置文件: vim /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/welcome.conf 跳转页面到 /var/w ...
- JAVA 中转义符的理解
生物信息中有时候会遇到JAVA写的程序,今天阅读源码的时候发现对于正则中的转义符不好理解,后来查资料后终于弄明白了,这里详细说明一下: 字符串的表示有三种方法:1.直接单字符,例如"A&qu ...
- Fiddler实现对手机抓包
工具 && 前提条件: 1. 安装了Fiddler的PC一台 2. 手机一部 3. 手机和PC是在同一个局域网内,或者至少能够联通,即手机的流量能够转发到PC端上能够被其捕获 PC端 ...