Java IO(三) 之 FileInputStream

來源:互聯網
上載者:User

標籤:java   io   輸入資料流   

前言:
對於檔案系統中的檔案,都可以使用FileInputStream流類以二進位的形式進行讀取,但是由於Java本身的定位在JVM之上,沒有處理電腦底層的能力,因此一些涉及底層處理的方法都是使用native方法調用第三方底層語言進行處理的。
本人重在講解FileInputStream類的內部實現,不會對其應用過分的講解。

FileInputStream的類圖:

解析:
FileInputStream重載了3個構造方法,可以通過以下三種方式初始輸入資料流:
public FileInputStream(String name) throws FileNotFoundException;
:以路徑的方式初始一個輸入資料流,其內部調用的是下面的構造方法
public FileInputStream(File file) throws FileNotFoundException;
:以File執行個體的方法初始一個輸入資料流
public FileInputStream(FileDescriptor fdObj);
:以FileDescriptor執行個體初始一個輸入資料流(FileDescriptor是一個檔案描述符)

FileInputStream內部記錄了幾個屬性,用來標識輸入資料流的狀態:
private final String path;
:檔案的路徑資訊
private final Object closeLock = new Object();
:關閉時的同步鎖
private volatile boolean closed = false;

FileInputStream內部,有幾個native類型的方法,用於調用底層語言來完整對於檔案系統的操作:
private native void open0(String name) throws FileNotFoundException;
:開啟檔案
private native int read0() throws IOException;
:讀取一個位元組
private native int readBytes(byte b[], int off, int len) throws IOException;
:讀取指定位元組數
public native long skip(long n) throws IOException;
:丟棄指定位元組,下次讀取時,從丟棄後的位置開始讀取
public native int available() throws IOException;
:擷取檔案接下來的檔案長度
private static native void initIDs();
private native void close0() throws IOException;
:關閉檔案
FileInputStream流類內部提供了一種對於檔案操作的機制,但是由於Java語言的局限,FileInputStream需要通過native方法調用底層語言實現。
如下簡單樣本:

public class FileInTest {    public static void main(String[] args) throws FileNotFoundException {        InputStream is = new FileInputStream("F:/shiro-config.ini");        int i;        try {            i = is.read();            while (i != -1) {                System.out.println((char) i);                i = is.read();            }            is.close();        } catch (IOException e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        }    }}

在實際應用中,FileInputStream並不常單獨使用,需要與其他裝飾流一起使用,來達到更加簡便的操作檔案。

其他的IO流在本系列文章中會一一講解。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java IO(三) 之 FileInputStream

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.