我们清楚读取文件数据使用缓冲数组读取效率更高,sun也知道使用缓冲数组读取效率更高,那么
这时候sun给我们提供了一个——缓冲输入字节流对象,让我们可以更高效率读取文件。

推荐使用自己的缓冲数组输入字节流读取效率高!

输入字节流体系:

—-| InputStream 输入字节流的基类。 抽象
———-| FileInputStream 读取文件数据的输入字节流
———-| BufferedInputStream 缓冲输入字节流 缓冲输入字节流的出现主要是为了提高读取文件数据的效率。

其实该类内部维护了一个8kb的字节数组。

注意:

凡是缓冲流都不具备读写文件的能力。只能读取!!!

使用BufferedInputStream的步骤 :

1. 找到目标文件。
2. 建立数据 的输入通道
3. 建立缓冲 输入字节流流
4. 关闭资源

缓冲数组读取与缓冲输入字节流读取案例:


public class Demo1 {

public static void main(String[] args) throws IOException {
readTest2();
}

public static void readTest2() throws IOException{
//找到目标文件
File file = new File("F:\\a.txt");
//BufferedInputStrem本身是不具备读文件的能力,所以需要借助FileInputStream来读取文件的数据。
FileInputStream fileInputStream= new FileInputStream(file);
BufferedInputStream bufferedInputStream= new BufferedInputStream(fileInputStream);
bufferedInputStream.read();



FileOutputStream fileOutputStream= new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream= new BufferedOutputStream(fileOutputStream);
fileOutputStream.write(null);

//读取文件数据
int content = 0 ;
//疑问二:BufferedInputStream出现 的目的是了提高读取文件的效率,但是BufferedInputStream的read方法每次读取一个字节的数据。

//而FileInputStreram每次也是读取一个字节的数据,那么BufferedInputStream效率高从何而来?

//查看源码得知因为BufferedInputStream内部利用内部的8kb字节数组,内部read()方法,每次都是从内存读取。而FileInputStreram是从硬盘,所以读取速度高。(其实差别不大)

while((content = fileInputStream.read())!=-1){
System.out.print((char)content);
}

//关闭资源
bufferedInputStream.close();//调用BufferedInputStream的close方法实际上关闭的是FileinputStream.
}



//读取文件的时候我们都是使用缓冲数组读取。效率会更加高
public static void readTest() throws IOException{
File file = new File("F:\\a.txt");
//建立数组通道
FileInputStream fileInputStream = new FileInputStream(file);
//建立缓冲数组读取数据
byte[] buf = new byte[1024*8];
int length = 0;
while((length = fileInputStream.read(buf))!=-1){
System.out.print(new String(buf,0,length));
}
//关闭资源
fileInputStream.close();
}


}

更多相关文章

  1. Java中字符流和字节流到底有什么区别!!!
  2. 理顺 JavaScript (12) - 一个比较实用的数组用法
  3. Java IO流系列(四)—— 从字节流及其缓冲区到转换流
  4. 如何在泽西Rest Webservice中接受json数组输入
  5. java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.c
  6. 给定一个整数数组,找出两个下标,要求后面下标所指的数减去前面下标
  7. Java中怎么把字符串数组转为整形数组
  8. Java——IO类,字节流读数据
  9. 剑指Offer(六)旋转数组的最小数字(Java版 )

随机推荐

  1. RobotFramework中加载自定义python包中的
  2. jmeter 调用python的方法三种 (还没试)
  3. 将muilti维Json数组解析为Python
  4. python常用数据类型-字典
  5. 为什么Python的eval()拒绝这个多行字符串
  6. python3编写网络爬虫21-scrapy框架的使用
  7. python中None与Null的区别
  8. [LeetCode] 126. Word Ladder II 词语阶
  9. Pandas 文本数据方法 findall( )
  10. 错误:在windows7中安装psycopg2时无法找到