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中 ...
随机推荐
- 文本分类学习 (五) 机器学习SVM的前奏-特征提取(卡方检验续集)
前言: 上一篇比较详细的介绍了卡方检验和卡方分布.这篇我们就实际操刀,找到一些训练集,正所谓纸上得来终觉浅,绝知此事要躬行.然而我在躬行的时候,发现了卡方检验对于文本分类来说应该把公式再变形一般,那样 ...
- mysql中binlog与存储引擎的2PC
mysql内部的2PC mysql开启binlog后实际上可以认为其数据有两份,binlog中一份,引擎中一份(这里先把存储引擎中数据看成整体的单独一份,另外也可以把binlog看成是一个引擎).既然 ...
- 基于SSE4和多核编程的电子相册的实现
基于SSE4和多核编程的电子相册的实现 摘要:电子相册中前后两张图片的切换会产生淡入淡出效果,而且切换过程中需要大量的中间计算过程,而SSE4和多核编程技术能够有效加快中间的计算过程,有效减少图片 ...
- SVN提交时显示:Path is not a working copy directory
说明你地址没有checkout啊 先checkout,才能add和commi. 要是在一个已有的项目出现这个错误,就是包含这个地址的文件夹没添加进去,去上一层再试一次. 总之,养成在项目根目录提交的习 ...
- Linux文件基本操作
TIP:Tab键可以自动补全命令 首先要了解Linux树形结构 1./- 根每一个文件和目录从根目录开始.只有root用户具有该目录下的写权限.请注意,/root是root用户的主目录,这与/.不一样 ...
- VueJs(3)---V-指令
VueJs(3)---V-指令(1) 一.语法 v- 指令是带有v-的特殊属性 v-if 条件渲染 v-show v-else (必须在v-if/v-else-if/v-show指令后) v-else ...
- 将Python当作计算器
在交互模式中,最近一个表达式的值赋给变量 _.这样我们就可以把它当作一个桌面计算器,很方便的用于连续计算.例如: >>> price = 1.25 #声明变量price >&g ...
- 预习视频day1
课前预习 编译型和解释型语言优缺点 python2,pyhon3的宏观(大环境下)区别 python的种类 python编码规则 变量命名规范,常量 注释 1.编译型语言:将源码一次性转化为二进制代码 ...
- C stat函数的用法举例(转载)
stat函数讲解表头文件: #include <sys/stat.h> #include <unistd.h>定义函数: int stat( ...
- CodeForces - 766B Mahmoud and a Triangle
[题意概述] 给定一串数,从中挑三个,判断能否组成一个有正面积的三角形,如果能就输出YES,否则就输出NO [题目分析] 将 n 个数从大到小进行排列,三个三个往下去判断,只要后两个的和比第一个大的时 ...