BufferedInputStream
字节缓冲输入流:
1.是一个高级流,内部维护一个缓冲区,默认8KB
2.读取文件数据时一次性尽可能读取到缓冲区大小的字节
3.read方法从缓冲区获取数据:当缓冲区全部读完,会再次从磁盘上读取数据存储到缓冲区
4.常用构造器 BufferedInputStream(InputStream is) BufferedInputStream(InputStream is,int size)
public class BufferedInputStreamDemo01 {
public static void main(String[] args) {
BufferedInputStream bis = null;
try{
bis = new BufferedInputStream(
new FileInputStream("D:/file1.txt"),10);
int ch = bis.read();
System.out.println((char)ch);
//一次性读取多点字节
byte[] byte = new byte[10];
int length = -1;
for((length = bis.read(byte)) != -1){
String str =new String(byte,0,length);
System.out.println(str);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferOutputStream
字节缓冲输出:
1. 内部维护了一个字节数组作为缓冲区(缓存) : 默认值是8KB 2. 当我们写数据时,是先写到缓存中的, 并不是直接写到磁盘上。当缓存满的情况下,再一次性将数据写到磁盘,从而减少了与磁盘的交互次数,提高了写出效率。 3.最后一次写入到缓存后,有可能没有装满,可以调用flush方法,将其强制写到磁盘上 4.构造器:BuffertOutputStream(OutputSream os) BuffertOutputStream(OutputSream os,int size)size用于自定义缓冲区的大小
public class BufferedOutputStreamDemo01 {
public static void main(String[] args) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try{
fos = new FileOutputStream("D:/file2.txt",true);
bos new BufferOutStream(fos);
bos.write('A');
byte[] bytes = "hello word".getBytes("UTF-8");
bos.write(bytes,0,bytes.length);
bos.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
/*
* 多个流的关闭顺序: 应该先关闭高级流,然后再关低级流
* 不过,可以直接关闭高级流。
*/
// bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}