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中 ...
随机推荐
- Python Django rest framework
本节内容 Django rest framework 安装 Django rest framwwork 环境配置 简单举例说明 Django中使用 rest framework 1.1 安装 Djan ...
- SSM框架原理,作用及使用方法(非原创)
原帖:地址https://blog.csdn.net/bieleyang/article/details/77862042 如有侵权请联系删除 作用: SSM框架是spring MVC ,spring ...
- Jenkins的关闭、重启
以前一直用从cmd进入jenkins的安装目录,执行jenkins stop/start,但是新的jenkins有更加方便功能 关闭jenkins服务 只需要在访问jenkins服务器的网址url地址 ...
- Jupyter notebook 输出含中文的pdf 方法
我电脑 OS 是 Ubuntu14.04, 可用的最简单方法是: 打开终端,输入 sudo find / -name article.tplx 用以查找 article.tplx 文件位置,我电脑的结 ...
- python学习之路web框架续
中间件 django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法. 在django项 ...
- Oracle知识梳理(一)理论篇:基本概念和术语整理
理论篇:基本概念和术语整理 一.关系数据库 关系数据库是目前应用最为广泛的数据库系统,它采用关系数据模型作为数据的组织方式,关系数据模型由关系的数据结构,关系的操作集合和关系的完整 ...
- FJUT寒假作业第二周C题解(位运算)
题目来源:http://210.34.193.66:8080/vj/Contest.jsp?cid=161#P2 题意比较好理解.如果直接按题目要求一步一解.一定超时.作为一个懒人也不会这么暴力一个肯 ...
- 干货!一次kafka卡顿事故排查过程
由于一次功能上线后,导致某数据量急剧下滑,给我们紧张的呢!排查过程也是个学习过程(这其中有大部分是领导们的功劳,不过分享给大家应该也不犯法吧,ᐓ) 1. 确认问题的真实性? 被数据部门告知,某数据量下 ...
- Linux(十七)动态监控进程
17.1 介绍 top与ps命令很相似.它们都用来显示正在执行的进程.top与ps最大的不同之处,在于top在执行一段时间可以更新正在运行的进程 17.2 语法 top [选项] 常用选项 ...
- ROS探索总结(十九)——如何配置机器人的导航功能
1.概述 ROS的二维导航功能包,简单来说,就是根据输入的里程计等传感器的信息流和机器人的全局位置,通过导航算法,计算得出安全可靠的机器人速度控制指令.但是,如何在特定的机器人上实现导航功能包的功能, ...