学习更多源码,请关注微信公众号:jdkSpring ,或者微信扫一下二维码:
BufferedOutputStream 是缓冲输出流。它继承于FilterOutputStream。
BufferedOutputStream 的作用是为另一个输出流提供“缓冲功能”。
import java.io.*;
public class BufferedOutputStreamDemo {
public static void main(String[] args) throws Exception{
/**
* 把字符串写入文本
*/
String out = "qwertyuiopasdfghjklzxcvbnm";
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("D:\\jdk_s_d\\out.txt"));
outputStream.write(out.getBytes());
outputStream.flush();
outputStream.close();
/**
* 把一个文件的内容写入另外一个文件
*/
BufferedInputStream bf = new BufferedInputStream(new FileInputStream(new File("D:\\jdk_s_d\\BufferedInputStream.txt")));
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream("D:\\jdk_s_d\\out.txt"));
//追加
//BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream("D:\\jdk_s_d\\out.txt", true));
byte [] bytes = new byte[1024];
int j;
while ((j = bf.read(bytes)) != -1) {
//os.write(bytes);
String bs = new String(bytes, 0, j);
os.write(bs.getBytes());
}
os.flush();
bf.close();
os.close();
}
}
源码(JDK1.8)
public class BufferedOutputStream extends FilterOutputStream {
/**
* 存储数据的内部缓冲区.
*/
protected byte buf[];
/**
* 缓冲区中的有效字节数. 大小范围为[0, buf.length].
*/
protected int count;
/**
* 创建新的缓冲输出流以将数据写入指定的输出流
*
* @param out the underlying output stream.
*/
public BufferedOutputStream(OutputStream out) {
this(out, 8192);
}
/**
* 创建新的缓冲输出流以将数据写入指定的输出流
* 并指定缓冲区大小
* @param out the underlying output stream.
* @param size the buffer size.
* @exception IllegalArgumentException if size <= 0.
*/
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
/** 刷新内部缓冲区 */
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
/**
* 将指定的字节写入此缓冲输出流
*
* @param b the byte to be written.
* @exception IOException if an I/O error occurs.
*/
public synchronized void write(int b) throws IOException {
if (count >= buf.length) {
flushBuffer();
}
buf[count++] = (byte)b;
}
/**
* 从指定的字节数组写入缓冲输出流,范围从off开始len个字节
*/
public synchronized void write(byte b[], int off, int len) throws IOException {
if (len >= buf.length) {
/* 如果请求长度超过输出缓冲区的大小,刷新输出缓冲区,然后直接写入数据。*/
flushBuffer();
out.write(b, off, len);
return;
}
if (len > buf.length - count) {//len大于缓冲区剩余大小
flushBuffer();
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
/**
* 刷新此缓冲输出流。这将强制将任何缓冲输出字节写入输出流
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public synchronized void flush() throws IOException {
flushBuffer();
out.flush();
}
}