日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

BufferedInputStream與FileInputStream的區別

作者:好的OK Txtcyvy 更新時間: 2022-08-15 編程語言

InputStream是java標準庫提供的最基本的輸入流,
而FileInputStream是InputStream的一個子類,FileInputStream就是從文件流中讀取數據

7d791fbcbb6344a1892ac35c4afea85f.png
例如:
public class Text {
? ? public static void main(String[] args) throws IOException {
? ? ? ? try (InputStream in = new FileInputStream("D:\\javadata\\BASE03\\Test1")) {
? ? ? ? ? ? int data = -1;
? ? ? ? ? ? while ((data = in.read()) != -1) {
? ? ? ? ? ? ? ? System.out.print(data);
? ? ? ? ? ? }
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
}

而BufferedInputStream是緩沖輸入流,使用緩沖區提高文件的讀取效率,繼承自FilterInputStream,

它的本質是通過一個內部緩沖區數組實現的

例如在新建某輸入流對應的BufferedInputStream后,我們通過read()讀取輸入流的數據時,BufferedInputStream會將該輸入流的數據分批的填入到緩沖區中,每當緩沖區中的數據被讀完之后,輸入流會再次填充數據緩沖區,如此反復直到我們讀完輸入流數據位置。

977ffe1c123c489b9231f457d8ddc829.png

BufferedInputStream的作用是為其輸入流提供緩沖功能

創建BufferedInputStream時,需要通過它的構造函數指定某個輸入流為參數

例如:
public class Main {
? ? public static void main(String[] args) throws IOException {
? ? ? ? // 指定要讀取文件的緩沖輸入字節流
? ? ? ? try (BufferedInputStream in = new BufferedInputStream(new ????????????????FileInputStream("D:\\javadata\\Text\\1.txt"))) {
? ? ? ? ? ? byte[] buff = new byte[128];// 用來存儲每次讀取到的字節數組
? ? ? ? ? ? int len;// 每次讀取到的字節數組的長度
? ? ? ? ? ? while ((len = in.read(buff)) != -1) {
? ? ? ? ? ? ? ? System.out.println(Arrays.toString(buff));
? ? ? ? ? ? }
? ? ? ? }catch (IOException e){
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
}

原文鏈接:https://blog.csdn.net/qq_50587186/article/details/124972218

欄目分類
最近更新