天天看點

Java進階程式設計之IO流Java IO流

Java IO流

一、File類的使用

1. File類的了解

  • File類的一個對象,代表一個檔案或一個檔案目錄(俗稱:檔案夾)。
  • java.io.File類:

    檔案和檔案目錄路徑的抽象表示形式

    ,與平台無關。
  • File類中涉及到關于檔案或檔案目錄的建立、删除、重命名、修改時間、檔案大小等方法,但

    File類沒有涉及到寫入或讀取檔案内容的操作

    。如果

    需要寫入或讀取檔案内容的操作,必須使用 IO流(輸入/輸出流)來完成

  • 想要在Java程式中表示一個真實存在的檔案或目錄,那麼必須有一個File對象,但是Java程式中的一個File對象,可能沒有一個真實存在的檔案或目錄

  • 後續File類的對象常會作為參數傳遞到流的構造器中,指明讀取或寫入的"終點"。

2. File的執行個體化

2.1 常用構造器

  • File(String filePath)

    以filePath為路徑建立File對象,

    可以是絕對路徑和相對路徑

    ,如果filePath是相對路徑,則預設目前路徑在系統屬性user.dir中存儲。
    1. 絕對路徑

      :是一個固定路徑,從盤符開始
    2. 相對路徑

      :是相對于某個位置開始
  • File(String parent,String child)

    以parent為父路徑,child為子路徑建立File對象(child子路徑可以是檔案或檔案目錄)

  • File(File parent,String childPath)

    根據一個父File對象和子檔案路徑建立File對象

代碼示例:

@Test
public void test1() {
    //構造器1
    File file1 = new File("hello.txt");
    File file2 = new File("E:\\workspace\\JavaSenic\\day8\\hello.txt");
    System.out.println(file1);//==>  hello.txt
    System.out.println(file2);//==>  E:\workspace\JavaSenic\day8\hello.txt
    //構造器2 
    File file3 = new File("E:\\workspace\\JavaSenior\\day8", "hello.txt");
    System.out.println(file3);//==>  E:\workspace\JavaSenior\day8\hello.txt
  
    File file4 = new File("E:\\workspace", "JavaSenior");
    System.out.println(file4);//==>  E:\workspace\JavaSenior

    //構造器3
    File file5 = new File(file3, "hi.txt");
    System.out.println(file5);//==>  E:\workspace\JavaSenior\day8\hello.txt\hi.txt
}
           

2.2 路徑分類

  • 相對路徑:相較于某個路徑下,指明的路徑。
  • 絕對路徑:包含盤符在内的檔案或檔案目錄的路徑。

說明:

  • IDEA中:
    • 如果使用JUnit中的單元測試方法測試,相對路徑即為目前Module下。
    • 如果使用main()測試,相對路徑即為目前的Project下。
  • Eclipse中:
    • 不管使用單元測試方法還是使用main()測試,相對路徑都是目前的Project下。

2.3 路徑分隔符

  • 路徑中的每級目錄之間用一個

    路徑分隔符

    隔開。不同作業系統路徑分隔符也不一樣。
  • windows和DOS系統預設使用“\”來表示
  • UNIX和URL使用“/”來表示
  • Java程式支援跨平台運作,是以路徑分隔符要慎用

  • 為了解決這個隐患,File類提供了一個常量:

    public static final String separator

    。根據作業系統,動态的提供分隔符。

    舉例:

    //windows和DOS系統
    File file1 = new File("E:\\io\\test.txt");
    
    //UNIX和URL
    File file = new File("E:/io/test.txt");
    
    //java提供的常量File.separator
    File file = new File("E:"+File.separator+"io"+File.separator+"test.txt");
               

3. File類的常用方法

3.1 File類的擷取功能

  • public String getAbsolutePath():擷取絕對路徑
  • public String getPath() :擷取路徑
  • public String getName() :擷取名稱
  • public String getParent():擷取上層檔案目錄路徑。若無,傳回null
  • public long length() :擷取檔案長度(即:位元組數)。不能擷取目錄的長度。
  • public long lastModified() :擷取最後一次的修改時間,毫秒值

    如下的兩個方法适用于檔案目錄

  • public String[] list() :擷取指定目錄下的所有檔案或者檔案目錄的名稱數組
  • public File[] listFiles() :擷取指定目錄下的所有檔案或者檔案目錄的File數組

代碼示例:

@Test
public void test2(){
    File file1 = new File("hello.txt");
    File file2 = new File("d:\\io\\hi.txt");

    System.out.println(file1.getAbsolutePath());//E:\Java\day08\hello.txt
    System.out.println(file1.getPath());//hello.txt
    System.out.println(file1.getName());//hello.txt
    System.out.println(file1.getParent());
    System.out.println(file1.length());
    System.out.println(new Date(file1.lastModified()));

    System.out.println();

    System.out.println(file2.getAbsolutePath());// d:\io\hi.txt
    System.out.println(file2.getPath());// d:\io\hi.txt
    System.out.println(file2.getName());// hi.txt
    System.out.println(file2.getParent());// d:\io
    System.out.println(file2.length());
    System.out.println(file2.lastModified());
}
@Test
public void test3(){
    File file = new File("D:\\workspace_idea1\\JavaSenior");

    String[] list = file.list();
    for(String s : list){
        System.out.println(s);
    }

    System.out.println();

    File[] files = file.listFiles();
    for(File f : files){
        System.out.println(f);
    }

}
           

3.2 File類的重命名功能

  • public boolean renameTo(File dest):把檔案重命名為指定的檔案路徑
  • 注意:file1.renameTo(file2)為例:要想保證傳回true,需要file1在硬碟中是存在的,且file2不能在硬碟中存在。

代碼示例:

@Test
public void test4(){
    File file1 = new File("hello.txt");//hello.txt存在
    File file2 = new File("D:\\hi.txt");//hi.txt不存在
    boolean renameTo = file2.renameTo(file1);
    System.out.println(renameTo);//true, 再執行一遍就是flase
    
    //執行效果file1存在,file2不存在,執行後傳回true,并且hello.txt删除了,而hi.txt則建立出來并且内容是hello.txt中的内容。(把原檔案移動到指定路徑,包括其内容,隻是檔案名字改變為指定的)
}
           

3.3 File類的判斷功能

  • public boolean isDirectory():判斷是否是檔案目錄
  • public boolean isFile() :判斷是否是檔案
  • public boolean exists() :判斷是否存在
  • public boolean canRead() :判斷是否可讀
  • public boolean canWrite() :判斷是否可寫
  • public boolean isHidden() :判斷是否隐藏

代碼示例:

@Test
public void test5(){
    File file1 = new File("hello.txt");
    file1 = new File("hello1.txt");

    System.out.println(file1.isDirectory());
    System.out.println(file1.isFile());
    System.out.println(file1.exists());
    System.out.println(file1.canRead());
    System.out.println(file1.canWrite());
    System.out.println(file1.isHidden());

    System.out.println();

    File file2 = new File("d:\\io");
    file2 = new File("d:\\io1");
    System.out.println(file2.isDirectory());
    System.out.println(file2.isFile());
    System.out.println(file2.exists());
    System.out.println(file2.canRead());
    System.out.println(file2.canWrite());
    System.out.println(file2.isHidden());

}
           

3.4 File類的建立功能

建立硬碟中對應的檔案或檔案目錄:

  • public boolean createNewFile() :建立檔案。若檔案存在,則不建立,傳回false
  • public boolean mkdir() :建立檔案目錄。如果此檔案目錄存在,就不建立了。如果此檔案目錄的上層目錄不存在,也不建立。
  • public boolean mkdirs() :建立檔案目錄。如果此檔案目錄存在,就不建立了。如果上層檔案目錄不存在,一并建立。

注意事項:如果建立的檔案或者檔案目錄沒有寫盤符路徑,預設在項目路徑下

代碼示例:

@Test
public void test6() throws IOException {
    File file1 = new File("hi.txt");
    if(!file1.exists()){
        //檔案的建立
        file1.createNewFile();
        System.out.println("建立成功");
    }else{//檔案存在
        file1.delete();
        System.out.println("删除成功");
    }


}
@Test
public void test7(){
    //檔案目錄的建立
    File file1 = new File("d:\\io\\io1\\io3");

    boolean mkdir = file1.mkdir();
    if(mkdir){
        System.out.println("建立成功1");
    }

    File file2 = new File("d:\\io\\io1\\io4");

    boolean mkdir1 = file2.mkdirs();
    if(mkdir1){
        System.out.println("建立成功2");
    }
    //要想删除成功,io4檔案目錄下不能有子目錄或檔案
    File file3 = new File("D:\\io\\io1\\io4");
    file3 = new File("D:\\io\\io1");
    System.out.println(file3.delete());
}
           

3.5 File類的删除功能

删除磁盤中的檔案或檔案目錄

  • public boolean delete():删除檔案或者檔案夾
  • 删除注意事項

    Java中的删除不走資源回收筒。

    要删除一個檔案目錄,請注意該檔案目錄内不能包含檔案或者檔案目錄。

4. 記憶體解析

Java進階程式設計之IO流Java IO流

5. 小練習

利用File構造器,new一個檔案目錄file :

(1)在其中建立多個檔案和目錄

(2)編寫方法,實作删除fle中指定檔案的操作

@Test
public void test1() throws IOException {
    File file = new File("E:\\io\\io1\\hello.txt");
    //建立一個與file同目錄下的另外一個檔案,檔案名為:haha.txt
    File destFile = new File(file.getParent(),"haha.txt");
    boolean newFile = destFile.createNewFile();
    if(newFile){
        System.out.println("建立成功!");
    }
}
           

判斷指定目錄下是否有字尾名為jpg的檔案,如果有,就輸出該檔案名稱

public class FindJPGFileTest {

    @Test
    public void test1(){
        File srcFile = new File("d:\\code");

        String[] fileNames = srcFile.list();
        for(String fileName : fileNames){
            if(fileName.endsWith(".jpg")){
                System.out.println(fileName);
            }
        }
    }
    @Test
    public void test2(){
        File srcFile = new File("d:\\code");

        File[] listFiles = srcFile.listFiles();
        for(File file : listFiles){
            if(file.getName().endsWith(".jpg")){
                System.out.println(file.getAbsolutePath());
            }
        }
    }
    
    /*
	 * File類提供了兩個檔案過濾器方法
	 * public String[] list(FilenameFilter filter)
	 * public File[] listFiles(FileFilter filter)

	 */
    @Test
    public void test3(){
        File srcFile = new File("d:\\code");

        File[] subFiles = srcFile.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jpg");
            }
        });

        for(File file : subFiles){
            System.out.println(file.getAbsolutePath());
        }
    }

}
           

周遊指定目錄所有檔案名稱,包括子檔案目錄中的檔案。

拓展1:并計算指定目錄占用空間的大小

拓展2:删除指定檔案目錄及其下的所有檔案

public class ListFileTest {

    public static void main(String[] args) {
        // 遞歸:檔案目錄
        /** 列印出指定目錄所有檔案名稱,包括子檔案目錄中的檔案 */

        //1.建立目錄對象
        File file = new File("E:\\test");

        //2.列印子目錄
        printSubFile(file);

    }

    /**
     * 遞歸方法周遊所有目錄下的檔案
     *
     * @param dir
     */
    public static void printSubFile(File dir) {
        //列印子目錄
        File[] files = dir.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {//如果為檔案目錄,則遞歸調用自身
                printSubFile(f);
            } else {
                System.out.println(f.getAbsolutePath());//輸出絕對路徑
            }
        }
    }

    // 拓展1:求指定目錄所在空間的大小
    // 求任意一個目錄的總大小
    public long getDirectorySize(File file) {
        // file是檔案,那麼直接傳回file.length()
        // file是目錄,把它的下一級的所有大小加起來就是它的總大小
        long size = 0;
        if (file.isFile()) {
            size += file.length();
        } else {
            File[] allFiles = file.listFiles();// 擷取file的下一級
            // 累加all[i]的大小
            for (File f : allFiles) {
                size += getDirectorySize(f);//f的大小
            }
        }
        return size;
    }

    /**
     * 拓展2:删除指定的目錄
     */
    public void deleteDirectory(File file) {
        // 如果file是檔案,直接delete
        // 如果file是目錄,先把它的下一級幹掉,然後删除自己
        if (file.isDirectory()) {
            File[] allFiles = file.listFiles();
            //遞歸調用删除file下一級
            for (File f : allFiles) {
                deleteDirectory(f);
            }
        } else {
            //删除檔案
            file.delete();
        }
    }
}
           

二、IO流概述

1. 簡述

  • IO是Input/Output的縮寫,I/O技術是非常實用的技術,用于

    處理裝置之間的資料傳輸

    。如讀/寫檔案,網絡通訊等。
  • Java程式中,對于資料的輸入輸出操作以 “流(stream)” 的方式進行。
  • Java.IO包下提供了各種“流”類和接口,用以擷取不同種類的資料,并通過

    标準的方法

    輸入或輸出資料。

2. 流的分類

(1)按操作資料機關:位元組流、字元流

  • 對于文本檔案(.txt,.java,.c,.cpp),使用字元流處理
  • 對于非文本檔案(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用位元組流處理

(2) 按資料的流向:輸入流、輸出流

  • 輸入流input:讀取外部資料(磁盤、CD光牒等儲存設備的資料)到程式(記憶體)中。
  • 輸出流output:将程式(記憶體)資料輸出到磁盤、CD光牒等儲存設備中。

(3)按流的角色:節點流、處理流

  • 節點流:直接從資料源或目的地讀寫資料。
Java進階程式設計之IO流Java IO流
  • 處理流:不直接連接配接到資料源或目的地,而是“連接配接”在已存在的流(節點流或處理流)之上,通過對資料的處理為程式提供更為強大的讀寫功能。(就是“套接”在已有的流上)
Java進階程式設計之IO流Java IO流

圖示:

Java進階程式設計之IO流Java IO流
Java進階程式設計之IO流Java IO流

3. IO流的體系結構

3.1 總體分類

Java進階程式設計之IO流Java IO流
紅框為抽象基類,藍框為常用IO流

3.2 常用的幾個IO流結構

抽象基類 節點流(或檔案流) 緩沖流(處理流的一種)
InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer))
OutputSteam FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush()
Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine())
Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush()

3.3 常用節點流和處理流

(1) 常用節點流

Java進階程式設計之IO流Java IO流
  • File檔案流

    :對檔案進行讀、寫操作 :FileReader、FileWriter、FileInputStream、FileOutputStream。
  • 字元串

    :對字元串進行處理的節點流: StringReader、 StringWriter
  • 數組

    :對數組進行處理的節點流(對應的不再是檔案,而是記憶體中的一個數組): ByteArrayInputStream 、ByteArrayOutputStream、 CharArrayReader 、CharArrayWriter 。
  • Pipe管道流

    :實作管道的輸入和輸出(程序間通信): PipedReader與PipedWriter、PipedInputStream與PipedOutputStream。

(2) 常用處理流

Java進階程式設計之IO流Java IO流
  • 緩沖流

    :在讀入或寫出時,對資料進行緩存,避免頻繁讀寫硬碟:BufferedReader與BufferedWriter、BufferedInputStream與BufferedOutputStream。
  • 濾流

    :在資料進行讀或寫時進行過濾:FilterReader與FilterWriter、FilterInputStream與FilterOutputStream。
  • 轉換流

    :實作位元組流和字元流之間的轉換InputStreamReader、OutputStreamWriter。
  • 對象流

    :ObjectInputStream、ObjectOutputStream。
  • 資料流

    :按基本資料類型讀、寫(處理的資料是Java的基本類型(如布爾型,位元組,整數和浮點數)):DataInputStream、DataOutputStream 。
  • 計數流

    :在讀入資料時對行記數 :LineNumberReader、LineNumberInputStream。
  • 預讀流

    :通過緩存機制,進行預讀 :PushbackReader、PushbackInputStream。
  • 列印流

    :包含友善的列印方法 :PrintWriter、PrintStream。

3.4 抽象基類的說明:

抽象基類 位元組流 字元流
輸入流 InputSteam Reader
輸出流 OutputSteam Writer
  • 說明:Java的lO流共涉及40多個類,實際上非正常則,都是從如下4個抽象基類派生的。
  • 由這四個類派生出來的子類名稱都是以其父類名作為子類名字尾。
3.4.1 InputSteam & Reader
  • InputStream和Reader是所有輸入流的基類。
  • InputStream(典型實作:FileInputStream)
    • int read()
    • int read(byte[] b)
    • int read(byte[] b,int off,int len)
  • Reader(典型實作:FileReader)
    • int read()
    • int read(char[] c)
    • int read(char[] c,int off,int len)
  • 程式中打開的檔案IO資源不屬于記憶體裡的資源,垃圾回收機制無法回收該資源,是以應該顯式關閉檔案IO資源。
  • FileInputStream從檔案系統中的某個檔案中獲得輸入位元組。FileInputStream用于讀取非文本資料之類的原始位元組流。要讀取字元流,需要使用 FileReader。

InputSteam:

  • int read()

    從輸入流中讀取資料的下一個位元組。傳回0到255範圍内的int位元組值。如果因為已經到達流末尾而沒有可用的位元組,則傳回值-1。

  • int read(byte[] b)

    從此輸入流中将最多b.length個位元組的資料讀入一個byte數組中。如果因為已經到達流末尾而沒有可用的位元組,則傳回值-1.否則以整數形式傳回實際讀取的位元組數。

  • int read(byte[] b,int off,int len)

    将輸入流中最多len個資料位元組讀入byte數組。嘗試讀取len個位元組,但讀取的位元組也可能小于該值。以整數形式傳回實際讀取的位元組數。如果因為流位于檔案末尾而沒有可用的位元組,則傳回值-1。

  • public void close throws IOException

    關閉此輸入流并釋放與該流關聯的所有系統資源。

Reader:

  • int read()

    讀取單個字元。作為整數讀取的字元,範圍在0到65535之間(0x00-0xffff)(2個位元組的 Unicode碼),如果已到達流的末尾,則傳回-1。

  • int read(char[] cbuf)

    将字元讀入數組。如果已到達流的末尾,則傳回-1。否則傳回本次讀取的字元數。

  • int read(char[] cbuf,int off,int len)

    将字元讀入數組的某一部分。存到數組cbuf中,從off處開始存儲,最多讀len個字元。如果已到達流的末尾,則傳回-1。否則傳回本次讀取的字元數。

  • public void close throws IOException

    關閉此輸入流并釋放與該流關聯的所有系統資源

3.4.2 OutputSteam & Writer
  • OutputStream和Writer也非常相似:
    • void write(int b/int c);
    • void write(byte[] b/char[] cbuf);
    • void write(byte[] b/char[] buff,int off,int len);
    • void flush();
    • void close();需要先重新整理,再關閉此流
  • 因為字元流直接以字元作為操作機關,是以 Writer可以用字元串來替換字元數組,即以 String對象作為參數
    • void write(String str);
    • void write(String str,int off,int len);
  • FileOutputStream從檔案系統中的某個檔案中獲得輸出位元組。FileOutputstream用于寫出非文本資料之類的原始位元組流。要寫出字元流,需要使用 FileWriter

OutputStream:

  • void write(int b)

    将指定的位元組寫入此輸出流。 write的正常協定是:向輸出流寫入一個位元組。要寫入的位元組是參數b的八個低位。b的24個高位将被忽略。即寫入0~255範圍的

  • void write(byte[] b)

    将b.length個位元組從指定的byte數組寫入此輸出流。write(b)的正常協定是:應該與調用wite(b,0,b.length)的效果完全相同。

  • void write(byte[] b,int off,int len)

    将指定byte數組中從偏移量off開始的len個位元組寫入此輸出流。

  • public void flush()throws IOException

    重新整理此輸出流并強制寫出所有緩沖的輸出位元組,調用此方法訓示應将這些位元組立即寫入它們預期的目标。

  • public void close throws IOException

    關閉此輸岀流并釋放與該流關聯的所有系統資源。

Writer:

  • void write(int c)

    寫入單個字元。要寫入的字元包含在給定整數值的16個低位中,16高位被忽略。即寫入0到65535之間的 Unicode碼。

  • void write(char[] cbuf)

    寫入字元數組

  • void write(char[] cbuf,int off,int len)

    寫入字元數組的某一部分。從off開始,寫入len個字元

  • void write(String str)

    寫入字元串。

  • void write(String str,int off,int len)

    寫入字元串的某一部分。

  • void flush()

    重新整理該流的緩沖,則立即将它們寫入預期目标。

  • public void close throws IOException

    關閉此輸出流并釋放與該流關聯的所有系統資源

4. 輸入、輸出标準化過程

4.1 輸入過程:

① 建立File類的對象,指明讀取的資料的來源。(要求此檔案一定要存在)

② 建立相應的輸入流,将File類的對象作為參數,傳入流的構造器中

③ 具體的讀入過程:建立相應的byte[] 或 char[]。

④ 關閉流資源

說明:程式中出現的異常需要使用try-catch-finally處理。

4.2 輸出過程:

① 建立File類的對象,指明寫出的資料的位置。(不要求此檔案一定要存在)

② 建立相應的輸出流,将File類的對象作為參數,傳入流的構造器中

③ 具體的寫出過程:write(char[]/byte[] buffer,0,len)

④ 關閉流資源

說明:程式中出現的異常需要使用try-catch-finally處理。

5. 流的關閉順序

  • 先關外層流,再關内層流(即一般指先關處理流,再關節點流)
  • 關閉外層流的同時,内層流也會自動的進行關閉。是以内層流的關閉,可以省略。

三、檔案流的使用

(節點流的一種)

1. 檔案字元流的使用

FileReader 和 FileWriter

1.1 檔案的輸入

從檔案中讀取到記憶體(程式)中。 (檔案 —>記憶體/程式)

注意點:

  1. read()的了解:傳回讀入的一個字元。如果達到檔案末尾,傳回-1
  2. 異常的處理:為了保證流資源一定可以執行關閉操作。需要使用try-catch-finally處理
  3. 讀入的檔案一定要存在,否則就會報FileNotFoundException。

步驟:

  1. 建立一個流對象,将已存在的一個檔案加載進流 FileReader fr = new FileReader(new File(“hello. txt”));
  2. 建立一個臨時存放資料的數組 char[] ch = new char[1024];
  3. 調用流對象的讀取方法将流中的資料讀入到數組中。 fr.read(ch);
  4. 關閉資源。 fr.close();

代碼示例:

@Test
public void testFileReader1()  {
    FileReader fr = null;
    try {
        //1.File類的執行個體化
        File file = new File("hello.txt");//hello.txt内容為hello123

        //2.FileReader流的執行個體化
        fr = new FileReader(file);

        //3.讀入的操作
        //read(char[] cbuf):傳回每次讀入cbuf數組中的字元的個數。如果達到檔案末尾,傳回-1
        char[] cbuf = new char[5];
        int len;
        while((len = fr.read(cbuf)) != -1){
            /***方式一***/
            //錯誤寫法,因為第二次123覆寫第一次内容中的前三個,即123lo,是以最終讀出:hello123lo
            for(int i = 0,i<cbuf.length;i++){
                System.out.print(cbuf[i]);
            }
            //正确寫法
            for(int i = 0,i<len;i++){
                System.out.print(cbuf[i]);
            }
            
            /***方式二**/
            //錯誤寫法,最後讀取出來是hello123lo,正确的應該是hello123
            String str = new String(cbuf);
            //正确寫法:把一個數組cbuf從0取到len,取出來之後轉換成String類型
            String str = new String(cbuf,0,len);
            
            System.out.print(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fr != null){
            //4.資源的關閉
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
           

1.2 檔案的輸出

從記憶體(程式)寫出到硬碟檔案中。(記憶體/程式 —>檔案)

注意點:

  • 輸出操作,對應的File是可以不存在的,并不會報異常。

    (1) File如果不存在,在輸出的過程中,會自動建立此檔案,并寫入相應内容。

    (2) File如果存在:

    ① 如果流使用的構造器是:FileWriter(file,flase) /FileWriter(file),會對原有檔案内容進行覆寫

    ② 如果流使用的構造器是:FileWriter(file,true) ,不會對原有檔案内容進行覆寫,而是在原有檔案内容上進行追加。

步驟:

  1. 建立流對象,建立資料存放檔案 File Writer fw = new File Writer(new File(“Test.txt”))
  2. 調用流對象的寫入方法,将資料寫入流 fw.write(“HelloWord”)
  3. 關閉流資源,并将流中的資料清空到檔案中。 fw.close();

代碼示例:

@Test
public void testFileWriter() {
    FileWriter fw = null;
    try {
        //1.提供File類的對象,指明寫出到的檔案
        File file = new File("hello1.txt");

        //2.提供FileWriter的對象,用于資料的寫出
        fw = new FileWriter(file,false);

        //3.寫出的操作
        fw.write("I have a dream!\n");
        fw.write("you need to have a dream!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.流資源的關閉
        if(fw != null){

            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           

1.3 小練習

實作文本檔案的複制操作

@Test
public void testFileReaderFileWriter() {
    FileReader fr = null;
    FileWriter fw = null;
    try {
        //1.建立File類的對象,指明讀入和寫出的檔案
        File srcFile = new File("hello.txt");
        File destFile = new File("hello2.txt");

        //不能使用字元流來處理圖檔等位元組資料
        // File srcFile = new File("狗.jpg");
        // File destFile = new File("狗1.jpg");

        //2.建立輸入流和輸出流的對象
        fr = new FileReader(srcFile);
        fw = new FileWriter(destFile);

        //3.資料的讀入和寫出操作
        char[] cbuf = new char[5];
        int len;//記錄每次讀入到cbuf數組中的字元的個數
        while((len = fr.read(cbuf)) != -1){
            //每次寫出len個字元
            fw.write(cbuf,0,len);

        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.關閉流資源
        try {
            if(fw != null)
                fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if(fr != null)
                fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
           

2. 檔案位元組流的使用

FileInputSteam 和 FileOutputSteam

檔案位元組流操作與字元流操作類似,隻是執行個體化對象操作和資料類型不同。

注意點:

  • 對于文本檔案(.txt,.java,.c,.cpp),使用字元流處理
  • 對于非文本檔案(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用位元組流處理

代碼示例:

//使用位元組流FileInputStream處理文本檔案,可能出現亂碼。
@Test
public void testFileInputStream() {
    FileInputStream fis = null;
    try {
        //1. 造檔案
        File file = new File("hello.txt");

        //2.造流
        fis = new FileInputStream(file);

        //3.讀資料
        byte[] buffer = new byte[5];
        int len;//記錄每次讀取的位元組的個數
        while((len = fis.read(buffer)) != -1){

            String str = new String(buffer,0,len);
            System.out.print(str);

        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fis != null){
            //4.關閉資源
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
           

小練習

實作圖檔檔案複制操作

@Test
public void testFileInputOutputStream()  {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        //1.建立File對象
        File srcFile = new File("狗.jpg");
        File destFile = new File("狗2.jpg");

        //2.建立操流
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);

        //3.複制的過程
        byte[] buffer = new byte[5];
        int len;
        while((len = fis.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.關閉流
        if(fos != null){
            //
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
           

3. 注意點

  • 定義路徑時,可以用“/”或“\”。
  • 輸出操作,對應的File可以不存在的。并不會報異常。
  • File對應的硬碟中的檔案如果不存在,在輸出的過程中,會自動建立此檔案。
  • File對應的硬碟中的檔案如果存在:
    • 如果流使用的構造器是:FileWriter(file,false) / FileWriter(file):對原有檔案的覆寫。
    • 如果流使用的構造器是:FileWriter(file,true):不會對原有檔案覆寫,而是在原有檔案基礎上追加内容。
  • 讀取檔案時,必須保證檔案存在,否則會報異常。
  • 對于文本檔案(.txt,.java,.c,.cpp),使用字元流處理
  • 對于非文本檔案(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用位元組流處理
  • 如果對于文本檔案,隻是想複制一下,不在記憶體層面讀出來,用位元組流也可以。而對于非文本檔案,就一定不能用字元流處理。

四、緩沖流的使用

( 處理流的一種 )

1. 緩沖流:

  • BufferedInputStream
  • BufferedOutputStream
  • BufferedReader
  • BufferedWriter

2. 作用:

  • 作用:提供流的讀取、寫入的速度
  • 提高讀寫速度的原因:内部提供了一個緩沖區。預設情況下是8KB
Java進階程式設計之IO流Java IO流

處理流與節點流的對比圖示

Java進階程式設計之IO流Java IO流
Java進階程式設計之IO流Java IO流

3. 使用說明

  • 當讀取資料時,資料按塊讀入緩沖區,其後的讀操作則直接通路緩沖區。
  • 當使用 BufferedInputStream讀取位元組檔案時,BufferedInputStream會一次性從檔案中讀取8192個(8Kb),存在緩沖區中,直到緩沖區裝滿了,才重新從檔案中讀取下一個8192個位元組數組。
  • 向流中寫入位元組時,不會直接寫到檔案,先寫到緩沖區中直到緩沖區寫滿,BufferedOutputStream才會把緩沖區中的資料一次性寫到檔案裡。使用方法flush()可以強制将緩沖區的内容全部寫入輸出流。
  • 關閉流的順序和打開流的順序相反。隻要關閉最外層流即可,關閉最外層流也會相應關閉内層節點流。
  • flush()方法的使用:手動将buffer中内容寫入檔案。
  • 如果是帶緩沖區的流對象的close()方法,不但會關閉流,還會在關閉流之前重新整理緩沖區,關閉後不能再寫出。

代碼示例:

3.1 非文本檔案的複制

使用BufferInputStream和BufferOutputStream實作

@Test
public void testBufferedStream(){
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        //1.造檔案
        File srcFile = new File("狗.jpg");
        File destFile = new File("狗1.jpg");
        //2.造流
        //2.1造節點流
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        //2.2造緩沖流
        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);

        //3.檔案複制操作:讀取、寫入
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1){
            bos.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.關閉流
        //要求:先關外層流,再關内層流(這裡指先關緩沖流,再關節點流)
        //說明:關閉外層流的同時,内層流也會自動的進行關閉。關于内層流的關閉,可以省略
          if (bos != null){
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bis != null){

            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           

3.2 文本檔案的複制

使用BufferedReader和BufferedWriter實作

@Test
public void testBufferedReaderBufferedWriter(){
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        //建立檔案和相應的流
        br = new BufferedReader(new FileReader(new File("dbcp.txt")));
        bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));

        //讀寫操作
        //方式一:使用char[]數組
        //char[] cbuf = new char[1024];
        //int len;
        //while((len = br.read(cbuf)) != -1){
        //bw.write(cbuf,0,len);
        // // bw.flush();
        //            }

        //方式二:使用String
        String data;
        while((data = br.readLine()) != null){//readLine()一行一行的進行讀取
            //方法一:
            // bw.write(data + "\n");//data中不包含換行符,用"\n"換行
            //方法二:
            bw.write(data);//data中不包含換行符
            bw.newLine();//提供換行的操作

        }


    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //關閉資源
        if(bw != null){

            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(br != null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
           

4. 小練習

4.1 緩沖流和節點流複制速度

節點流實作複制方法

//指定路徑下檔案的複制
public void copyFile(String srcPath,String destPath){
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        //1.造檔案
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);

        //2.造流
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);

        //3.複制的過程
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fos != null){
            //4.關閉流
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

緩沖流實作複制操作

//實作檔案複制的方法
public void copyFileWithBuffered(String srcPath,String destPath){
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {
        //1.造檔案
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
        //2.造流
        //2.1 造節點流
        FileInputStream fis = new FileInputStream((srcFile));
        FileOutputStream fos = new FileOutputStream(destFile);
        //2.2 造緩沖流
        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);

        //3.複制的細節:讀取、寫入
        byte[] buffer = new byte[1024];
        int len;
        while((len = bis.read(buffer)) != -1){
            bos.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.資源關閉
        //要求:先關閉外層的流,再關閉内層的流
        if(bos != null){
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if(bis != null){
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

測試二者速度

@Test
public void testCopyFileWithBuffered(){
    long start = System.currentTimeMillis();
    String srcPath = "C:\\Users\\Administrator\\Desktop\\視訊1.avi";
    String destPath = "C:\\Users\\Administrator\\Desktop\\視訊2.avi";
    
    //節點流實作複制
	copyFile(scrPath,destPath);
    
    //緩沖流實作複制
    copyFileWithBuffered(srcPath,destPath);
    
    long end = System.currentTimeMillis();
    
	System.out.println("節點流——複制操作花費的時間為:" + (end - start));//618
    System.out.println("緩沖流——複制操作花費的時間為:" + (end - start));//176
}
           

4.2 實作圖檔加密操作

加密操作

  • 将圖檔檔案通過位元組流讀取到程式中
  • 将圖檔的位元組流逐一進行異或^操作
  • 将處理後的圖檔位元組流輸出
//圖檔的加密
@Test
public void test1() {

    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream("狗.jpg");
        fos = new FileOutputStream("狗Secret.jpg");

        byte[] buffer = new byte[20];
        int len;
        while ((len = fis.read(buffer)) != -1) {

            for (int i = 0; i < len; i++) {
                buffer[i] = (byte) (buffer[i] ^ 5);//異或操作
            }

            fos.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

解密操作

  • 将加密後圖檔檔案通過位元組流讀取到程式中
  • 将圖檔的位元組流逐一進行操作(原理:AB^B = A)
  • 将處理後的圖檔位元組流輸出
//圖檔的解密
@Test
public void test2() {

    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream("狗Secret.jpg");
        fos = new FileOutputStream("狗狗4.jpg");

        byte[] buffer = new byte[20];
        int len;
        while ((len = fis.read(buffer)) != -1) {
          
            for (int i = 0; i < len; i++) {
                buffer[i] = (byte) (buffer[i] ^ 5);
            }

            fos.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

4.3 統計文本字元出現次數

實作思路:

  1. 周遊文本每一個字元
  2. 字元出現的次數存在Map中
  3. 把map中的資料寫入檔案
@Test
public void testWordCount() {
    FileReader fr = null;
    BufferedWriter bw = null;
    try {
        //1.建立Map集合
        Map<Character, Integer> map = new HashMap<Character, Integer>();

        //2.周遊每一個字元,每一個字元出現的次數放到map中
        fr = new FileReader("dbcp.txt");
        int c = 0;
        while ((c = fr.read()) != -1) {
            //int 還原 char
            char ch = (char) c;
            // 判斷char是否在map中第一次出現
            if (map.get(ch) == null) {
                map.put(ch, 1);
            } else {
                map.put(ch, map.get(ch) + 1);
            }
        }

        //3.把map中資料存在檔案count.txt
        //3.1 建立Writer
        bw = new BufferedWriter(new FileWriter("wordcount.txt"));

        //3.2 周遊map,再寫入資料
        Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entrySet) {
            switch (entry.getKey()) {
                case ' ':
                    bw.write("空格=" + entry.getValue());
                    break;
                case '\t'://\t表示tab 鍵字元
                    bw.write("tab鍵=" + entry.getValue());
                    break;
                case '\r'://
                    bw.write("回車=" + entry.getValue());
                    break;
                case '\n'://
                    bw.write("換行=" + entry.getValue());
                    break;
                default:
                    bw.write(entry.getKey() + "=" + entry.getValue());
                    break;
            }
            bw.newLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.關流
        if (fr != null) {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (bw != null) {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

五、轉換流

位元組流和字元流之間的轉換

,按操作資料它屬于

字元流

,按流角色分屬于

處理流

1. 簡介

  • 轉換流提供了在位元組流和字元流之間的轉換
  • Java API提供了兩個轉換流:
    • InputstreamReader:将Inputstream轉換為Reader

    • OutputStreamWriter:将Writer轉換為OutputStream

  • 位元組流中的資料都是字元時,轉成字元流操作更高效。
  • 很多時候我們使用轉換流來處理檔案亂碼問題。實作編碼和解碼的功能。

圖示:

Java進階程式設計之IO流Java IO流

1.1 InputStreamReader

  1. 将一個位元組的輸入流轉換為字元的輸入流

  2. 解碼: 位元組、位元組數組 ===> 字元數組、字元串
  3. 構造器:
  • public InputStreamReader(InputStream in) //

    使用系統預設的編碼集

  • public InputStreamReader(Inputstream in,String charsetName) //charsetName

    指定編碼集

    ,如utf-8

1.2 OutputStreamWriter

  1. 将一個字元的輸出流轉換為位元組的輸出流

  2. 編碼:字元數組、字元串 ===> 位元組、位元組數組
  3. 構造器:
  • public OutputStreamWriter(OutputStream out) //

    使用系統預設的編碼集

  • public OutputStreamWriter(Outputstream out,String charsetName)//可以指定編碼集,如utf-8、GBK

2. 代碼示例:

/**
綜合使用InputStreamReader和OutputStreamWriter
     */
@Test
public void test1() {
    InputStreamReader isr = null;
    OutputStreamWriter osw = null;
    try {
        //1.造檔案、造流
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_gbk.txt");

        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
		//new InputStreamReader(fis);使用系統預設的編碼集
        //參數2指明字元集,具體使用哪個字元集,取決于dbcp.txt檔案一開始儲存時使用的字元集
        isr = new InputStreamReader(fis, "utf-8");
        osw = new OutputStreamWriter(fos, "gbk");

        //2.讀寫過程
        char[] cbuf = new char[20];
        int len;
        while ((len = isr.read(cbuf)) != -1){
            osw.write(cbuf,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.關流
        if (isr != null){

            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (osw != null){
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           
說明:檔案編碼的方式(比如:GBK),決定了解析時使用的字元集(也隻能是GBK)。

3. 字元編碼

3.1 編碼表的由來

計算機隻能識别二進制資料,早期由來是電信号。為了友善應用計算機,讓它可以識别各個國家的文字。就将各個國家的文字用數字來表示,并一一對應,形成一張表。這張表就是編碼表。

3.2 常見的字元集

  • ASCII:美國标準資訊交換碼。用一個位元組的7位可以表示。
  • ISO8859-1:拉丁碼表。歐洲碼表用一個位元組的8位表示。
  • GB2312:中國的中文編碼表。最多兩個位元組編碼所有字元
  • GBK:中國的中文編碼表更新,融合了更多的中文文字元号。最多兩個位元組編碼
  • Unicode:國際标準碼,融合了目前人類使用的所字元。為每個字元配置設定唯一的字元碼。所有的文字都用兩個位元組來表示。
  • UTF-8:變長的編碼方式,可用1-4個位元組來表示一個字元。
Java進階程式設計之IO流Java IO流

說明:

Java進階程式設計之IO流Java IO流

UTF-8變長編碼表示

Java進階程式設計之IO流Java IO流

執行個體:以漢字 “尚”為例

Java進階程式設計之IO流Java IO流

3.3 編碼應用

  • 編碼:字元串–>位元組數組
  • 解碼:位元組數組–>字元串
  • 轉換流的編碼應用
    • 可以将字元按指定編碼格式存儲
    • 可以對文本資料按指定編碼格式來解讀
    • 指定編碼表的動作由構造器完成

使用要求:

用戶端/浏覽器端 <=> 背景(java,GO,Python,Node.js,php) <=> 資料庫

要求前前後後使用的字元集都要統一:如UTF-8。

六、标準輸入、輸出流

Java進階程式設計之IO流Java IO流

1. 簡介

System.in:

标準的輸入流

,預設從鍵盤輸入

System.out:

标準的輸出流

,預設從控制台輸出

2. 主要方法

System類的setIn(InputStream is) :重新指定輸入的流

System類的setOut(PrintStream ps):重新指定輸出的流。

3. 使用示例

題目

:從鍵盤輸入字元串,要求将讀取到的整行字元串轉成大寫輸出。然後繼續進行輸入操作,

直至當輸入“e”或者“exit”時,退出程式。

設計思路

方法一:使用Scanner實作,調用next()傳回一個字元串

方法二:使用System.in實作。System.in —> 轉換流 —> BufferedReader的readLine()

public static void main(String[] args) {
    BufferedReader br = null;
    try {
        InputStreamReader isr = new InputStreamReader(System.in);
        br = new BufferedReader(isr);

        while (true) {
            System.out.println("請輸入字元串:");
            String data = br.readLine();
            if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
                System.out.println("程式結束");
                break;
            }

            String upperCase = data.toUpperCase();
            System.out.println(upperCase);

        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

4. 小練習

設計實作Scanner類

public class MyInput {
    //從鍵盤讀取字元串
    public static String readString() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        //聲明并初始化字元串
        String string = "";

        //從鍵盤上擷取字元串
        try {
            string = br.readLine();

        } catch (IOException ex) {
            System.out.println(ex);
        }

        //傳回從鍵盤擷取的字元串
        return string;
    }

    //從鍵盤讀取整型值
    public static int readInt() {
        return Integer.parseInt(readString());
    }

    // 從鍵盤讀取雙精度值
    public static double readDouble() {
        return Double.parseDouble(readString());
    }

    //從鍵盤讀取位元組值
    public static double readByte() {
        return Byte.parseByte(readString());
    }

    //從鍵盤讀取短整形值
    public static double readShort() {
        return Short.parseShort(readString());
    }

    //從鍵盤讀取長整形值
    public static double readLong() {
        return Long.parseLong(readString());
    }

    //從鍵盤讀取浮點值
    public static double readFloat() {
        return Float.parseFloat(readString());
    }
}
           

七、列印流

Java進階程式設計之IO流Java IO流

執行個體:

@Test
public void test2() {
    PrintStream ps = null;
    try {
        FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
        // 建立列印輸出流,設定為自動重新整理模式(寫入換行符或位元組 '\n' 時都會重新整理輸出緩沖區)
        ps = new PrintStream(fos, true);
        if (ps != null) {// 把标準輸出流(控制台輸出)改成檔案
            System.setOut(ps);
        }


        for (int i = 0; i <= 255; i++) { // 輸出ASCII字元
            System.out.print((char) i);
            if (i % 50 == 0) { // 每50個資料一行
                System.out.println(); // 換行
            }
        }


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (ps != null) {
            ps.close();
        }
    }

}
           

八、資料流

Java進階程式設計之IO流Java IO流

注意點:讀取不同類型的資料的順序要與當初寫入檔案時儲存的資料的順序一緻!

示例代碼:

将記憶體中的字元串、基本資料類型的變量寫出到檔案中。

@Test
public void test3(){
    //1.造對象、造流
    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(new FileOutputStream("data.txt"));
        //資料輸出
        dos.writeUTF("馬雲");
        dos.flush();//重新整理操作,将記憶體的資料寫入到檔案
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.關閉流
        if (dos != null){
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           

将檔案中存儲的基本資料類型變量和字元串讀取到記憶體中,儲存在變量中。

/*
注意點:讀取不同類型的資料的順序要與當初寫入檔案時,儲存的資料的順序一緻!
 */
@Test
public void test4(){
    DataInputStream dis = null;
    try {
        //1.造對象、造流
        dis = new DataInputStream(new FileInputStream("data.txt"));
        //2.從檔案讀入資料
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();

        System.out.println("name:"+name);
        System.out.println("age:"+age);
        System.out.println("isMale:"+isMale);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.關閉流
        if (dis != null){

            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           

九、對象流

1. 概述

Java進階程式設計之IO流Java IO流

2. 作用:

  • ObjectOutputStream:記憶體中的對象 ==> 存儲中的檔案、通過網絡傳輸出去(序列化過程)
  • ObjectInputStream:存儲中的檔案、通過網絡接收過來 ==> 記憶體中的對象(反序列化過程)

3. 對象的序列化

Java進階程式設計之IO流Java IO流
Java進階程式設計之IO流Java IO流

4. 對象序列化的條件:

  1. 需要實作接口:

    Serializable

    (辨別接口)
  2. 目前類提供一個全局常量:serialVersionUID(序列版本号)
  3. 除了目前Person類需要實作Serializable接口之外,還必須保證其内部所有屬性也必須是可序列化的。(預設情況下,基本資料類型可序列化;還有需序列化的屬性,不能用static,transient 修飾)

補充:ObjectOutputStream 和 ObjectInputStream不能序列化

static

transient

修飾的成員變量。即

static,transient 修飾的屬性不能被序列化

示例:

//自定義類Person
public class Person implements Serializable {
    public static final long serialVersionUID = 131545142L;//随意,保證唯一就行
    private String name;
    private int age;
    private Account account;

    public Person() {
    }

    public Person(String name, int age, Account account) {
        this.name = name;
        this.age = age;
        this.account = account;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", account=" + account +
                '}';
    }
}

class Account implements Serializable{
    
    public static final long serialVersionUID = 4855615152L;
    private Double blance;

    public Account() {
    }

    public Account(Double blance) {
        this.blance = blance;
    }

    public Double getBlance() {
        return blance;
    }

    public void setBlance(Double blance) {
        this.blance = blance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "blance=" + blance +
                '}';
    }
}


           

5. 對象流的使用

5.1 序列化代碼實作

序列化:将對象寫入磁盤或進行網絡傳輸

要求被序列化對象必須實作序列化

@Test
public void testObjectOutputStream(){
    ObjectOutputStream oos = null;

    try {
        //1.建立對象,建立流
        oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
        //2.操作流
        oos.writeObject(new String("我愛北京天安門"));
        oos.flush();//重新整理操作
		
        //自定義對象實作序列化
        oos.writeObject(new Person("王銘",23));
        oos.flush();
		//自定義對象實作序列化
        oos.writeObject(new Person("張學良",23,1001,new Account(5000)));
        oos.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(oos != null){
            //3.關閉流
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

           

5.2 反序列化代碼實作

反序列化:将磁盤的對象資料源讀出

@Test
public void testObjectInputStream(){
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("object.dat"));
	
        Object obj = ois.readObject();
        String str = (String) obj;
        
		//自定義類反序列化
        Person p = (Person) ois.readObject();
        Person p1 = (Person) ois.readObject();

        System.out.println(str);
        System.out.println(p);
        System.out.println(p1);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if(ois != null){
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

6. 序列化和反序列化 (補充)

  • 把對象轉換為位元組序列的過程稱為對象的序列化。
  • 把位元組序列恢複為對象的過程稱為對象的反序列化。
什麼情況下會使用到序列化?

(1)把記憶體中對象的位元組序列永久地儲存到一個檔案中或者資料庫中的時候;

(2)用套接字在網絡上傳輸對象時

(3)想通過RMI(遠端方法調用)傳輸對象時

場景舉例:

(1)在很多應用中,需要對某些對象進行序列化,讓它們離開記憶體空間,入住實體硬碟,以便長期儲存。比如最常見的是Web伺服器中的Session對象,當有 10萬使用者并發通路,就有可能出現10萬個Session對象,記憶體可能吃不消,于是Web容器就會把一些session先序列化到硬碟中,等要用了,再把儲存在硬碟中的對象還原到記憶體中。

(2)當兩個程序在進行遠端通信時,彼此可以發送各種類型的資料。無論是何種類型的資料,都會以二進制序列的形式在網絡上傳送。發送方需要把這個Java對象轉換為位元組序列,才能在網絡上傳送;接收方則需要把位元組序列再恢複為Java對象。

十、随機存取檔案流

RandomAccessFile 類的使用

1. 簡介

  • RandomAccessFile聲明在java.io包下,但直接繼承于java.lang.Object類。并且它實作了DataInput和DataOutput接口,也就意味着它既可以輸入也可以輸出。
  • RandomAccessFile既可以作為一個輸入流,又可以作為一個輸出流
  • RandomAccessFile類支援 “随機通路” 的方式,程式可以直接跳到檔案的任意地方來讀、寫檔案
    • 支援隻通路檔案的部分内容
    • 可以向已存在的檔案後追加内容
  • RandomAccessFile對象包含一個記錄指針,用以标示目前讀寫處的位置
  • RandomaccessFile類對象可以自由移動記錄指針:
    • long getFilePointer()

      :擷取檔案記錄指針的目前位置
    • void seek(long pos)

      :将檔案記錄指針定位到pos位置

構造器:

public RandomAccessFile(File file,String mode)

public RandomAccessFile(String name,String mode)

2. 使用說明:

  1. 如果RandomAccessFile作為輸出流時,寫出到的檔案如果不存在,則在執行過程中自動建立。
  2. 如果寫出到的檔案存在,則會對原檔案内容進行覆寫。(預設情況下,從頭覆寫)
  3. 可以通過相關的操作,實作RandomAccessFile“插入”資料的效果。借助seek(int pos)方法
  4. 建立RandomAccessFile類執行個體需要指定一個

    mode參數

    ,該參數指定RandomAccessFile的

    通路模式

    :
    • r:以隻讀方式打開

    • rw:打開以便讀取和寫入

    • rwd:打開以便讀取和寫入;同步檔案内容的更新

    • rws:打開以便讀取和寫入;同步檔案内容和中繼資料的更新

  5. 如果模式為隻讀r,則不會建立檔案,而是會去讀取一個已經存在的檔案,讀取的檔案不存在則會出現異常。如果模式為rw讀寫,檔案不存在則會去建立檔案,存在則不會建立。

3. 使用示例

檔案的讀取和寫出操作

@Test
public void test1() {

    RandomAccessFile raf1 = null;
    RandomAccessFile raf2 = null;
    try {
        //1.建立對象,建立流
        raf1 = new RandomAccessFile(new File("test.jpg"),"r");
        raf2 = new RandomAccessFile(new File("test1.jpg"),"rw");
        //2.操作流
        byte[] buffer = new byte[1024];
        int len;
        while((len = raf1.read(buffer)) != -1){
            raf2.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.關閉流
        if(raf1 != null){
            try {
                raf1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if(raf2 != null){
            try {
                raf2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
           

使用RandomAccessFile實作資料的插入效果

@Test
public void test2(){
    RandomAccessFile raf1 = null;
    try {
        raf1 = new RandomAccessFile(new File("hello.txt"), "rw");//hello.txt内容:abcdefgh

        raf1.seek(3);//将指針調到角标為3的位置
        //raf1.write("xyz".getBytes()); //hello.txt内容變為:abcxyzgh
        //方式一
        //儲存指針3後面的所有資料到StringBuilder中
        StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
        byte[] buffer = new byte[20];
        int len;
        while ((len = raf1.read(buffer)) != -1){
        builder.append(new String(buffer,0,len));
        }//循環執行完指針已經到最後位置
         //調回指針到3位置,寫入“xyz”
          raf1.seek(3);
          raf1.write("xyz".getBytes());
         //将StringBuilder中的資料寫入到檔案中
        raf1.write(builder.toString().getBytes());

        //方式二
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[20];
        int len;
        while ((len = raf1.read(buffer)) != -1){
            baos.write(buffer);
        }
        //調回指針到3位置,寫入“xyz”
        raf1.seek(3);
        raf1.write("xyz".getBytes());
       
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (raf1 != null){
            try {
                raf1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
           

我們可以用RandomAccessFile這個類,來實作一個多線程斷點下載下傳的功能,用過下載下傳工具就知道,下載下傳前都會建立兩個臨時檔案,一個是與被下載下傳檔案大小相同的空檔案,另一個是記錄檔案指針的位置檔案,每次暫停的時候,都會儲存上一次的指針,然後斷點下載下傳的時候,會繼續從上一次的地方下載下傳,進而實作斷點下載下傳或上傳功能。

十一、流的基本應用總結

  • 流是用來處理資料的。
  • 處理資料時,一定要先明确資料源,與資料目的地資料源可以是檔案,可以是鍵盤資料目的地可以是檔案、顯示器或者其他裝置
  • 而流隻是在幫助資料進行傳輸,并對傳輸的資料進行處理,比如過濾處理、轉換處理等
  • 除去RandomAccessFile類外所有的流都繼承于四個基本資料流抽象類InputSteam、OutputSteam、Reader、Writer
  • 不同的操作流對應的字尾均為四個抽象基類中的某一個
Java進階程式設計之IO流Java IO流
  • 不同處理流的使用方式都是标準操作:
    • 建立檔案對象,建立相應的流
    • 處理流資料
    • 關閉流
    • 用try-catch-finally處理異常

十二、NIO

這裡對Path、Paths、Files的使用做一個簡單介紹。

1. NIO的說明:

  • Java NIO (New IO,Non-Blocking IO)是從Java 1.4版本開始引入的一套新的IO API,可以替代标準的Java IO API。
  • NIO與原來的IO同樣的作用和目的,但是使用的方式完全不同,

    NIO支援面向緩沖區的(IO是面向流的)、基于通道的IO操作

  • NIO将以更加高效的方式進行檔案的讀寫操作

  • JDK 7.0對NIO進行了極大的擴充,增強了對檔案處理和檔案系統特性的支援,稱他為 NIO.2。
**`Java API中提供了兩套NIO,一套是針對标準輸入輸出NIO,另一套就是網絡程式設計NIO`**
|-----java.nio.channels.Channel
      |---- FileChannel:處理本地檔案
      |---- SocketChannel:TCP網絡程式設計的用戶端的Channel
      |---- ServerSocketChannel:TCP網絡程式設計的伺服器端的Channel
      |---- DatagramChannel:UDP網絡程式設計中發送端和接收端的Channel
           

2. NIO.2中Path、Paths、Files類的使用

  • Path可以看成是File類的更新版本,實際引用的資源也可以不存在。
  • Files包含了大量靜态的工具方法來操作檔案。
  • Paths則包含了兩個傳回Path的靜态工廠方法。

2.1 Path接口

  • 早期的Java隻提供了一個File類來通路檔案系統,但File類的功能比較有限,所提供的方法性能也不高。而且,

    大多數方法在出錯時僅傳回失敗,并不會提供異常資訊

  • NIO.2為了彌補這種不足,引入了Path接口,代表一個平台無關的平台路徑,描述了目錄結構中檔案的位置。

    Path可以看成是File類的更新版本,實際引用的資源也可以不存在

  • 同時,NIO.2在java.nio.file包下還提供了Files、Paths工具類,Files包含了大量靜态的工具方法來操作檔案;Paths則包含了兩個傳回Path的靜态工廠方法。
2.1.1 Path的說明:

Path替換原有的File類。

  • 在以前IO操作都是這樣寫的:
    • import java.io.File
    • File file = new File("index.html");

  • 但在Java7中,我們可以這樣寫:
    • import java.nio.file.Path;
    • import java.nio.file.Paths;
    • Path path = Paths.get("index. html");

2.1.2 Paths類的使用
  • Paths類提供的靜态get()方法用來擷取Path對象:

    static Path get(String first, String….more)

    :用于将多個字元串串連成路徑

    static Path get(URI uri)

    :傳回指定uri對應的Path路徑

代碼示例

@Test
public void test1(){
    Path path1 = Paths.get("hello.txt");//new File(String filepath)

    Path path2 = Paths.get("E:\\", "test\\test1\\haha.txt");//new File(String parent,String filename);

    Path path3 = Paths.get("E:\\", "test");

    System.out.println(path1);
    System.out.println(path2);
    System.out.println(path3);

}
           
2.1.3 常用方法
  • String toString() : 傳回調用 Path 對象的字元串表示形式
  • boolean startsWith(String path) : 判斷是否以 path 路徑開始
  • boolean endsWith(String path) : 判斷是否以 path 路徑結束
  • boolean isAbsolute() : 判斷是否是絕對路徑
  • Path getParent() :傳回Path對象包含整個路徑,不包含 Path 對象指定的檔案路徑
  • Path getRoot() :傳回調用 Path 對象的根路徑
  • Path getFileName() : 傳回與調用 Path 對象關聯的檔案名
  • int getNameCount() : 傳回Path 根目錄後面元素的數量
  • Path getName(int idx) : 傳回指定索引位置 idx 的路徑名稱
  • Path toAbsolutePath() : 作為絕對路徑傳回調用 Path 對象
  • Path resolve(Path p) :合并兩個路徑,傳回合并後的路徑對應的Path對象
  • File toFile(): 将Path轉化為File類的對象

代碼示例

@Test
public void test2() {
    Path path1 = Paths.get("d:\\", "nio\\nio1\\nio2\\hello.txt");
    Path path2 = Paths.get("hello.txt");

    //String toString() : 傳回調用 Path 對象的字元串表示形式
    System.out.println(path1);

    //boolean startsWith(String path) : 判斷是否以 path 路徑開始
    System.out.println(path1.startsWith("d:\\nio"));
    //boolean endsWith(String path) : 判斷是否以 path 路徑結束
    System.out.println(path1.endsWith("hello.txt"));
    //boolean isAbsolute() : 判斷是否是絕對路徑
    System.out.println(path1.isAbsolute() + "~");
    System.out.println(path2.isAbsolute() + "~");
    //Path getParent() :傳回Path對象包含整個路徑,不包含 Path 對象指定的檔案路徑
    System.out.println(path1.getParent());
    System.out.println(path2.getParent());
    //		Path getRoot() :傳回調用 Path 對象的根路徑
    System.out.println(path1.getRoot());
    System.out.println(path2.getRoot());
    //Path getFileName() : 傳回與調用 Path 對象關聯的檔案名
    System.out.println(path1.getFileName() + "~");
    System.out.println(path2.getFileName() + "~");
    //int getNameCount() : 傳回Path 根目錄後面元素的數量
    //Path getName(int idx) : 傳回指定索引位置 idx 的路徑名稱
    for (int i = 0; i < path1.getNameCount(); i++) {
        System.out.println(path1.getName(i) + "*****");
    }

    //Path toAbsolutePath() : 作為絕對路徑傳回調用 Path 對象
    System.out.println(path1.toAbsolutePath());
    System.out.println(path2.toAbsolutePath());
    //Path resolve(Path p) :合并兩個路徑,傳回合并後的路徑對應的Path對象
    Path path3 = Paths.get("d:\\", "nio");
    Path path4 = Paths.get("nioo\\hi.txt");
    path3 = path3.resolve(path4);
    System.out.println(path3);

    //File toFile(): 将Path轉化為File類的對象
    File file = path1.toFile();//Path--->File的轉換

    Path newPath = file.toPath();//File--->Path的轉換

}
           

2.2 Files類

java.nio.file.Files用于操作檔案或目錄的工具類

2.2.1 Files類常用方法
  • Path copy(Path src, Path dest, CopyOption … how) : 檔案的複制

    要想複制成功,要求path1對應的實體上的檔案存在。path1對應的檔案沒有要求。

  • Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING);
  • Path createDirectory(Path path, FileAttribute<?> … attr) : 建立一個目錄

    要想執行成功,要求path對應的實體上的檔案目錄不存在。一旦存在,抛出異常。

  • Path createFile(Path path, FileAttribute<?> … arr) : 建立一個檔案

    要想執行成功,要求path對應的實體上的檔案不存在。一旦存在,抛出異常。

  • void delete(Path path) : 删除一個檔案/目錄,如果不存在,執行報錯
  • void deleteIfExists(Path path) : Path對應的檔案/目錄如果存在,執行删除.如果不存在,正常執行結束
  • Path move(Path src, Path dest, CopyOption…how) : 将 src 移動到 dest 位置

    要想執行成功,src對應的實體上的檔案需要存在,dest對應的檔案沒有要求。

  • long size(Path path) : 傳回 path 指定檔案的大小

代碼示例

@Test
public void test1() throws IOException{
    Path path1 = Paths.get("d:\\nio", "hello.txt");
    Path path2 = Paths.get("atguigu.txt");

    //Path copy(Path src, Path dest, CopyOption … how) : 檔案的複制
    //要想複制成功,要求path1對應的實體上的檔案存在。path1對應的檔案沒有要求。
    //Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING);

    //Path createDirectory(Path path, FileAttribute<?> … attr) : 建立一個目錄
    //要想執行成功,要求path對應的實體上的檔案目錄不存在。一旦存在,抛出異常。
    Path path3 = Paths.get("d:\\nio\\nio1");
    //Files.createDirectory(path3);

    //Path createFile(Path path, FileAttribute<?> … arr) : 建立一個檔案
    //要想執行成功,要求path對應的實體上的檔案不存在。一旦存在,抛出異常。
    Path path4 = Paths.get("d:\\nio\\hi.txt");
    //Files.createFile(path4);

    //void delete(Path path) : 删除一個檔案/目錄,如果不存在,執行報錯
    //Files.delete(path4);

    //void deleteIfExists(Path path) : Path對應的檔案/目錄如果存在,執行删除.如果不存在,正常執行結束
    Files.deleteIfExists(path3);

    //Path move(Path src, Path dest, CopyOption…how) : 将 src 移動到 dest 位置
    //要想執行成功,src對應的實體上的檔案需要存在,dest對應的檔案沒有要求。
    //Files.move(path1, path2, StandardCopyOption.ATOMIC_MOVE);

    //long size(Path path) : 傳回 path 指定檔案的大小
    long size = Files.size(path2);
    System.out.println(size);

}
           
2.2.2 Files類常用方法:用于判斷
  • boolean exists(Path path, LinkOption … opts) : 判斷檔案是否存在
  • boolean isDirectory(Path path, LinkOption … opts) : 判斷是否是目錄

    不要求此path對應的實體檔案存在。

  • boolean isRegularFile(Path path, LinkOption … opts) : 判斷是否是檔案
  • boolean isHidden(Path path) : 判斷是否是隐藏檔案

    要求此path對應的實體上的檔案需要存在。才可判斷是否隐藏。否則,抛異常。

  • boolean isReadable(Path path) : 判斷檔案是否可讀
  • boolean isWritable(Path path) : 判斷檔案是否可寫
  • boolean notExists(Path path, LinkOption … opts) : 判斷檔案是否不存在

代碼示例

@Test
public void test2() throws IOException{
    Path path1 = Paths.get("d:\\nio", "hello.txt");
    Path path2 = Paths.get("atguigu.txt");
    //boolean exists(Path path, LinkOption … opts) : 判斷檔案是否存在
    System.out.println(Files.exists(path2, LinkOption.NOFOLLOW_LINKS));

    //boolean isDirectory(Path path, LinkOption … opts) : 判斷是否是目錄
    //不要求此path對應的實體檔案存在。
    System.out.println(Files.isDirectory(path1, LinkOption.NOFOLLOW_LINKS));

    //boolean isRegularFile(Path path, LinkOption … opts) : 判斷是否是檔案

    //boolean isHidden(Path path) : 判斷是否是隐藏檔案
    //要求此path對應的實體上的檔案需要存在。才可判斷是否隐藏。否則,抛異常。
    //System.out.println(Files.isHidden(path1));

    //boolean isReadable(Path path) : 判斷檔案是否可讀
    System.out.println(Files.isReadable(path1));
    //boolean isWritable(Path path) : 判斷檔案是否可寫
    System.out.println(Files.isWritable(path1));
    //boolean notExists(Path path, LinkOption … opts) : 判斷檔案是否不存在
    System.out.println(Files.notExists(path1, LinkOption.NOFOLLOW_LINKS));
}
           

補充:

  • StandardOpenOption.READ:表示對應的Channel是可讀的。
  • StandardOpenOption.WRITE:表示對應的Channel是可寫的。
  • StandardOpenOption.CREATE:如果要寫出的檔案不存在,則建立。如果存在,忽略
  • StandardOpenOption.CREATE_NEW:如果要寫出的檔案不存在,則建立。如果存在,抛異常
2.2.3 Files類常用方法:用于操作内容
  • InputStream newInputStream(Path path, OpenOption…how):擷取 InputStream 對象
  • OutputStream newOutputStream(Path path, OpenOption…how) : 擷取 OutputStream 對象
  • SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 擷取與指定檔案的連接配接,how 指定打開方式。
  • DirectoryStream

    newDirectoryStream(Path path) : 打開 path 指定的目錄

代碼示例

@Test
public void test3() throws IOException{
    Path path1 = Paths.get("d:\\nio", "hello.txt");

    //InputStream newInputStream(Path path, OpenOption…how):擷取 InputStream 對象
    InputStream inputStream = Files.newInputStream(path1, StandardOpenOption.READ);

    //OutputStream newOutputStream(Path path, OpenOption…how) : 擷取 OutputStream 對象
    OutputStream outputStream = Files.newOutputStream(path1, StandardOpenOption.WRITE,StandardOpenOption.CREATE);


    //SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 擷取與指定檔案的連接配接,how 指定打開方式。
    SeekableByteChannel channel = Files.newByteChannel(path1, StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);

    //DirectoryStream<Path>  newDirectoryStream(Path path) : 打開 path 指定的目錄
    Path path2 = Paths.get("e:\\teach");
    DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path2);
    Iterator<Path> iterator = directoryStream.iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
    }
}
           

十三、BIO、NIO與AIO的差別(拓展)

這裡隻是簡單說明一下,而有關java中BIO、NIO與AIO的差別的詳細說明,請前往【BIO、NIO與AIO的差別】。

1. 首先來說一下什麼是I/O?

  • 在計算機系統中I/O就是輸入(Input)和輸出(Output)的意思,針對不同的操作對象,可以劃分為磁盤I/O模型,網絡I/O模型,記憶體映射I/O, Direct I/O、資料庫I/O等,隻要具有輸入輸出類型的互動系統都可以認為是I/O系統,也可以說I/O是整個作業系統資料交換與人機互動的通道,這個概念與選用的開發語言沒有關系,是一個通用的概念。
  • 在如今的系統中I/O卻擁有很重要的位置,現在系統都有可能處理大量檔案,大量資料庫操作,而這些操作都依賴于系統的I/O性能,也就造成了現在系統的瓶頸往往都是由于I/O性能造成的。是以,為了解決磁盤I/O性能慢的問題,系統架構中添加了緩存來提高響應速度;或者有些高端伺服器從硬體級入手,使用了固态硬碟(SSD)來替換傳統機械硬碟;在大資料方面,計算引擎(Spark)越來越多的承擔了實時性計算任務,而傳統的分布式系統基礎架構則大多應用在了離線計算與大量資料存儲的場景,這也是由于磁盤I/O性能遠不如記憶體I/O性能而造成的格局。是以,一個系統的優化空間,往往都在低效率的I/O環節上,很少看到一個系統CPU、記憶體的性能是其整個系統的瓶頸。也正因為如此,Java在I/O上也一直在做持續的優化,從JDK 1.4開始便引入了NIO模型,大大的提高了以往BIO模型下的操作效率。

2. BIO、NIO、AIO的基本定義

  • BIO (Blocking I/O):同步阻塞I/O模式,資料的讀取寫入必須阻塞在一個線程内等待其完成。這裡使用那個經典的燒開水例子,這裡假設一個燒開水的場景,有一排水壺在燒開水,BIO的工作模式就是, 叫一個線程停留在一個水壺那,直到這個水壺燒開,才去處理下一個水壺。但是實際上線程在等待水壺燒開的時間段什麼都沒有做。
  • NIO (New I/O):同時支援阻塞與非阻塞模式,但這裡我們以其同步非阻塞I/O模式來說明,那麼什麼叫做同步非阻塞?如果還拿燒開水來說,NIO的做法是叫一個線程不斷的輪詢每個水壺的狀态,看看是否有水壺的狀态發生了改變,進而進行下一步的操作。
  • AIO ( Asynchronous I/O):異步非阻塞I/O模型。異步非阻塞與同步非阻塞的差別在哪裡?異步非阻塞無需一個線程去輪詢所有IO操作的狀态改變,在相應的狀态改變後,系統會通知對應的線程來處理。對應到燒開水中就是,為每個水壺上面裝了一個開關,水燒開之後,水壺會自動通知我水燒開了。

3. 程序中的IO調用步驟

大緻可以分為以下四步:

  1. 程序向作業系統請求資料 ;
  2. 作業系統把外部資料加載到核心的緩沖區中;
  3. 作業系統把核心的緩沖區拷貝到程序的緩沖區 ;
  4. 程序獲得資料完成自己的功能 ;

當作業系統在把外部資料放到程序緩沖區的這段時間(即上述的第二,三步),如果應用程序是挂起等待的,那麼就是同步IO,反之,就是異步IO,也就是AIO 。

指定的目錄

代碼示例

@Test
public void test3() throws IOException{
    Path path1 = Paths.get("d:\\nio", "hello.txt");

    //InputStream newInputStream(Path path, OpenOption…how):擷取 InputStream 對象
    InputStream inputStream = Files.newInputStream(path1, StandardOpenOption.READ);

    //OutputStream newOutputStream(Path path, OpenOption…how) : 擷取 OutputStream 對象
    OutputStream outputStream = Files.newOutputStream(path1, StandardOpenOption.WRITE,StandardOpenOption.CREATE);


    //SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 擷取與指定檔案的連接配接,how 指定打開方式。
    SeekableByteChannel channel = Files.newByteChannel(path1, StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);

    //DirectoryStream<Path>  newDirectoryStream(Path path) : 打開 path 指定的目錄
    Path path2 = Paths.get("e:\\teach");
    DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path2);
    Iterator<Path> iterator = directoryStream.iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
    }
}
           

十三、BIO、NIO與AIO的差別(拓展)

這裡隻是簡單說明一下,而有關java中BIO、NIO與AIO的差別的詳細說明,請前往【BIO、NIO與AIO的差別】。

1. 首先來說一下什麼是I/O?

  • 在計算機系統中I/O就是輸入(Input)和輸出(Output)的意思,針對不同的操作對象,可以劃分為磁盤I/O模型,網絡I/O模型,記憶體映射I/O, Direct I/O、資料庫I/O等,隻要具有輸入輸出類型的互動系統都可以認為是I/O系統,也可以說I/O是整個作業系統資料交換與人機互動的通道,這個概念與選用的開發語言沒有關系,是一個通用的概念。
  • 在如今的系統中I/O卻擁有很重要的位置,現在系統都有可能處理大量檔案,大量資料庫操作,而這些操作都依賴于系統的I/O性能,也就造成了現在系統的瓶頸往往都是由于I/O性能造成的。是以,為了解決磁盤I/O性能慢的問題,系統架構中添加了緩存來提高響應速度;或者有些高端伺服器從硬體級入手,使用了固态硬碟(SSD)來替換傳統機械硬碟;在大資料方面,計算引擎(Spark)越來越多的承擔了實時性計算任務,而傳統的分布式系統基礎架構則大多應用在了離線計算與大量資料存儲的場景,這也是由于磁盤I/O性能遠不如記憶體I/O性能而造成的格局。是以,一個系統的優化空間,往往都在低效率的I/O環節上,很少看到一個系統CPU、記憶體的性能是其整個系統的瓶頸。也正因為如此,Java在I/O上也一直在做持續的優化,從JDK 1.4開始便引入了NIO模型,大大的提高了以往BIO模型下的操作效率。

2. BIO、NIO、AIO的基本定義

  • BIO (Blocking I/O):同步阻塞I/O模式,資料的讀取寫入必須阻塞在一個線程内等待其完成。這裡使用那個經典的燒開水例子,這裡假設一個燒開水的場景,有一排水壺在燒開水,BIO的工作模式就是, 叫一個線程停留在一個水壺那,直到這個水壺燒開,才去處理下一個水壺。但是實際上線程在等待水壺燒開的時間段什麼都沒有做。
  • NIO (New I/O):同時支援阻塞與非阻塞模式,但這裡我們以其同步非阻塞I/O模式來說明,那麼什麼叫做同步非阻塞?如果還拿燒開水來說,NIO的做法是叫一個線程不斷的輪詢每個水壺的狀态,看看是否有水壺的狀态發生了改變,進而進行下一步的操作。
  • AIO ( Asynchronous I/O):異步非阻塞I/O模型。異步非阻塞與同步非阻塞的差別在哪裡?異步非阻塞無需一個線程去輪詢所有IO操作的狀态改變,在相應的狀态改變後,系統會通知對應的線程來處理。對應到燒開水中就是,為每個水壺上面裝了一個開關,水燒開之後,水壺會自動通知我水燒開了。

3. 程序中的IO調用步驟

大緻可以分為以下四步:

  1. 程序向作業系統請求資料 ;
  2. 作業系統把外部資料加載到核心的緩沖區中;
  3. 作業系統把核心的緩沖區拷貝到程序的緩沖區 ;
  4. 程序獲得資料完成自己的功能 ;

當作業系統在把外部資料放到程序緩沖區的這段時間(即上述的第二,三步),如果應用程序是挂起等待的,那麼就是同步IO,反之,就是異步IO,也就是AIO 。