天天看點

java IO 位元組流(一)FileInputStream與FileOutputStream

與字元流不同,位元組流可以處理任意類型的檔案,其實從類的命名就可以很容易的區分哪些類是操作位元組流或者哪些類是操作字元流的,位元組流的都是以Stream結尾的,而操作字元流的類都是以Reader或Writer結尾的。

位元組流根據流向不同也可以分為兩類:

1.輸入流

以InputStream為父類的一系列操作位元組流的類,相對于記憶體而言,是将流讀取到記憶體中,是以是輸入流。

2.輸出流

以OutputStream為父類的一系列操作位元組流的類,相對于的記憶體而言,是将記憶體中的流輸出到檔案,是以為輸出流。

本篇主要總結一下FileInputStream與FileOutputStream

1.FileInputStream

主要用來讀取非文本資料的檔案,從源碼中可以知道構造方法有三種,常用的有兩種,并且這兩種可以算是一種,因為傳的如果是路徑,源碼中也會直接new一個File

java IO 位元組流(一)FileInputStream與FileOutputStream

注意:用位元組流讀取中文顯示到控制台會出現亂碼情況,是因為漢子占兩個位元組,而位元組流每次隻能讀取一個位元組,就把它轉為字元,寫入文本時不會出現這種情況

讀取時常用的有三種方式:

1.每次讀取一個byte數組,效率高(檢視源碼也是一次讀取一個位元組,存到byte數組中)

2.每次讀取一個位元組,效率低(一般說的低是指讀取一個寫入一個,效率肯定會慢)

3.建立的byte數組與流大小相等,使用于較小的檔案,不推薦使用,如果檔案過大會導緻byte數組建立失敗。

java IO 位元組流(一)FileInputStream與FileOutputStream

最後一定要關閉流

注:

選用文本時因為可以在控制台列印,其他的不能隻管的在控制台檢視,但是話說回來,輸入流都是為輸出流做準備的,沒有說在程式中列印某一部分流的,一般都是用來上傳下載下傳,或者複制檔案

2.FileOutputStream

FileOutputStream一般是與FileInputStream成對使用的,構造方法有五種,常用的有兩種,兩種可以做了解(多一個是否追加的參數,布爾值,預設FALSE),常用的兩種構造方法與FileInputStream一緻。

public FileOutputStream(String name) throws FileNotFoundException {

this(name != null ? new File(name) : null, false);

}

public FileOutputStream(String name, boolean append)
        throws FileNotFoundException
    {
        this(name != null ? new File(name) : null, append);
    }

    public FileOutputStream(File file) throws FileNotFoundException {
        this(file, false);
    }

    public FileOutputStream(File file, boolean append)
        throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");
        }
        this.fd = new FileDescriptor();
        fd.attach(this);
        this.append = append;
        this.path = name;

        open(name, append);
    }

    public FileOutputStream(FileDescriptor fdObj) {
        SecurityManager security = System.getSecurityManager();
        if (fdObj == null) {
            throw new NullPointerException();
        }
        if (security != null) {
            security.checkWrite(fdObj);
        }
        this.fd = fdObj;
        this.append = false;
        this.path = null;

        fd.attach(this);
    }
           

主要用來将流輸出,常用write方法,可以将單個位元組作為參數,也可以将byte數組作為參數,byte數組作為參數也是循環寫位元組

java IO 位元組流(一)FileInputStream與FileOutputStream

組合使用如下:

java IO 位元組流(一)FileInputStream與FileOutputStream

當然可以使用byte數組作為參數,也可以是圖檔,視訊等各種檔案,需要注意的是最後一定要将流關閉。