主頁 > 後端開發 > 學習筆記之IO流

學習筆記之IO流

2020-11-01 15:50:10 後端開發

IO流

File

File類概述

File:它是檔案和目錄路徑名的抽象表示

  • 檔案和目錄是可以通過File封裝成物件的
  • 對于File而言,其封裝性并不是一個真正存在的檔案,僅僅是一個路徑名而已,它可以是存在的,也可以是不存在的,將來要是用過具體的操作把這個路徑的內容轉換為具體存在的

構造方法

  1. File(String pathname) 通過將給定的路徑名字串轉換為抽象路徑名來創建新的File實體
  2. File(String parent,String child) 從路徑名字字串和子路徑名字字串創建新的File實體
  3. File(File parent,String child)從父抽象路徑名和子路徑名字字串創建新的File實體
import java.io.File;
public class Demo {
    public static void main(String[] args) {
        //File(String pathname) 通過將給定的路徑名字串轉換為抽象路徑名來創建新的File實體
        File f1 = new File("D:\\JAVA\\java.txt");
        System.out.println(f1);
        //File(String parent,String child) 從路徑名字字串和子路徑名字字串創建新的File實體
        File f2 = new File("D:\\JAVA","java.txt");
        System.out.println(f2);
        //File(File parent,String child)從父抽象路徑名和子路徑名字字串創建新的File實體
        File f3 = new File("D:\\JAVA");
        File f4 = new File(f3,"java.txt");
        System.out.println(f4);
    }
}

File類創建功能

  1. public boolean createNewFile() 當具有該名稱的檔案不存在時,創建一個由該抽象路徑命名的新空檔案

    • 檔案名存在,就不創建,回傳false
    • 檔案名不存在,就創建,回傳ture
  2. public boolean mkdir() 創建由此路徑名命名的目錄

    • 目錄名存在,就不創建,回傳false
    • 目錄名不存在,就創建,回傳ture
  3. punlic boolean mkdirs() 創建由此抽象路徑名命名的目錄,包括任何必須但不存在的父目錄

    • 目錄名存在,就不創建,回傳false
    • 目錄名不存在,就創建,回傳ture
import java.io.File;
import java.io.IOException;
public class Demo {
    public static void main(String[] args) throws IOException {
        //在D:\\JAVA目錄下創建一個檔案java.txt
        File f1 = new File("D:\\JAVA\\java.txt");
        System.out.println(f1.createNewFile());
        //在E:\\JAVA目錄下創建一個目錄JavaEE
        System.out.println("----------------");
        File f2 = new File("D:\\JAVA\\JAVAEE");
        System.out.println(f2.mkdir());
        //在E:\\JAVA目錄下創建一個多級目錄javaWEB\\HTML
        System.out.println("----------------");
        File f3 = new File("D:\\JAVA\\javaWEB\\HTML");
        System.out.println(f3.mkdirs());
    }
}


File判斷和獲取功能

  1. public boolean isDiectory() 測驗此抽象路徑名表示的File是否為目錄
  2. public boolean isFiel() 測驗此抽象路徑名表示的Fiel是否為檔案
  3. public boolean exists() 測驗此抽象路徑名表示的File是否存在
  4. public String getAbsolutePath() 回傳此抽象路徑名轉換為路徑名字字串
  5. public String getPath() 將此抽象路徑名轉換為路徑名字串
  6. public String getName() 回傳由此抽象路徑名表示的檔案或目錄的名稱
  7. public String[] list() 回傳此抽象路徑名表示的目錄中的檔案和目錄的名稱字串陣列
  8. public File[] listFiles() 回傳此抽象路徑名表示的目錄中的檔案和目錄的File物件陣列
import java.io.File;
public class Demo {
    public static void main(String[] args) {
//        1. public boolean isDiectory() 測驗此抽象路徑名表示的File是否為目錄
//        1. public boolean isFiel() 測驗此抽象路徑名表示的Fiel是否為檔案
//        3. public boolean exists() 測驗此抽象路徑名表示的File是否存在
        File f1 = new File("D:\\JAVA\\java.txt");
        System.out.println(f1.isDirectory());
        System.out.println(f1.isFile());
        System.out.println(f1.exists());
        System.out.println("---------------------------");
//        4. public String getAbsolutePath() 回傳此抽象路徑名轉換為路徑名字字串
//        5. public String getPath() 將此抽象路徑名轉換為路徑名字串
//        6. public String getName() 回傳由此抽象路徑名表示的檔案或目錄的名稱
        System.out.println(f1.getAbsolutePath());
        System.out.println(f1.getPath());
        System.out.println(f1.getName());
//        7. public String[] list() 回傳此抽象路徑名表示的目錄中的檔案和目錄的名稱字串陣列
//       8. public File[] listFiles() 回傳此抽象路徑名表示的目錄中的檔案和目錄的File物件陣列
        File f2 = new File("D:\\JAVA");
        String[] list = f2.list();
        System.out.println(list);
        for (String li : list) {
            System.out.println(li);
        }
        System.out.println("---------------------");
        File[] files = f2.listFiles();
        for (File filelist : files) {
//            System.out.println(filelist);
            if (filelist.isFile()) {
                System.out.println(filelist.getName());
            }
        }
    }
}


File類洗掉功能

  • public boolean delete() 洗掉由此抽象路徑名表示的檔案或目錄

遍歷目錄

/*
給定一個路徑(E:\\JAVA),請通過遞回完成遍歷該目錄下的所有內容,并把所有檔案的絕對路徑輸出到控制臺

思路:
根據給定路徑創建一個File物件
定義一個方法用于獲取給定目錄下的所有內容,引數為第一步創建的File物件
獲取給定的File目錄下所有的檔案或者目錄的File陣列
遍歷該File陣列,得到每一個File物件
判斷該File物件是否是目錄
    是:遞回呼叫
    不是:獲取絕對路徑輸出在控制臺
呼叫方法
 */
import java.io.File;
public class Demo {
    public static void main(String[] args) {
        File fiel = new File("D:\\JAVA");
        getAllFilePath(fiel);
    }
    public static void getAllFilePath(File file){
        File[] files = file.listFiles();
        if (files != null){
            for (File i : files){
                if (i.isDirectory()){
                    getAllFilePath(i);
                }else{
                    System.out.println(i.getAbsolutePath());
                }
            }
        }
    }
}

IO流概述和分類

IO流概述:

  • IO:輸入/輸出(input/Output)
  • 流 : 是一種抽象概念,是對資料傳輸的總稱,也就是說資料在設備間的傳輸稱為流,流的本質是資料傳輸
  • IO流就是用來處理設備間資料傳輸問題的
    • 常見的應用:檔案復制;檔案上傳;檔案下載

分類

  • 按資料流向:
    • 輸入流:讀資料
    • 輸出流:寫資料
  • 按照資料型別分
    • 位元組流
      • 位元組輸入流;位元組輸出流
    • 字符流
      • 字符輸入流;字符輸出流
  • 一般IO流按照資料型別來分

使用場景:

  • 如果資料通過Windows自帶的記事本,我們還可以讀懂里面的內容,用字符流;否則用位元組流,若不知道使用哪種型別,用位元組流(萬能流),

位元組流

位元組流抽象基類

  • InputStream:這個抽象類是表示位元組輸入流的所有類的超類
  • OutputStream:這個抽象類表示位元組輸出流的所有類的超類
  • 子類名特點:子類名稱都是以其父類名作為子類名的后綴

FileOutputStream:檔案輸出流用于將資料寫入File

  • FileOutputStream(String name):創建檔案輸出流以指定的名稱寫入檔案

使用位元組輸出流寫資料的步驟

  1. 創建位元組輸出流物件(呼叫系統功能創建了檔案,創建位元組輸出流物件,讓位元組輸出流物件指向檔案)
  2. 呼叫位元組輸出流物件的寫資料方法
  3. 釋放資源(關閉此檔案輸出流并釋放與此相關聯的任何系統資源)
/*
FileOutputStream(String name):創建檔案輸出流以指定的名稱寫入檔案
     做了三件事:
        呼叫系統功能創建了檔案
        創建了位元組輸出流物件
        讓位元組輸出流物件指向創建好的檔案
void write(int b):將指定的位元組寫入此檔案輸出流
最后都要釋放資源
void colse():關閉此檔案輸出流并釋放與此相關聯的任何系統資源
 */
 import java.io.FileOutputStream;
import java.io.IOException;
public class Demo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("fos.txt");
        fos.write(97);
        fos.close();
    }
}

位元組流寫資料的三種方式

  • void write(int b) 將指定的位元組寫入此檔案輸出流
  • void write(byte[] b)將b.length位元組從指定的位元組陣列寫入此檔案輸出流一次寫一個位元組陣列資料
  • void write(byte[] b, int off, int len)將len位元組從指定的位元組陣列開始,從偏移量off(索引位置)開始寫入此檔案輸出流一次寫一個位元組陣列的部分資料
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("fos.txt");
//void write(int b) 將指定的位元組寫入此檔案輸出流
//        fos.write(97);
//        fos.write(98);
//        fos.write(99);
//        fos.write(100);
//        fos.write(101);

//void write(byte[] b)將b.length位元組從指定的位元組陣列寫入此檔案輸出流一次寫一個位元組陣列資料
     byte[] bytes = "abcde".getBytes();
//        fos.write(bytes);

//void write(byte[] b, int off, int len)將len位元組從指定的位元組陣列開始,從偏移量off(索引位置)開始寫入此文
        fos.write(bytes,1,3);
    }
}
fos.colse();

寫入資料的兩個問題

  • 如何換行
    • Windows: \r\n
    • Linux: \n
    • mac: \r
  • 如何追加寫入
    • public FileOutputStream?(String name,boolean append)
      創建檔案輸出流以指定的名稱寫入檔案,
      如果第二個引數為true ,則位元組將寫入檔案的末尾而不是開頭,

import java.io.FileOutputStream;
import java.io.IOException;
public class Demo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("IO流\\fos.txt",true);
        //如何換行
        for (int i = 0; i < 10; i++){
            fos.write("hello".getBytes());
            //如何換行
            fos.write("\r\n".getBytes());
        }
        //釋放資源
    fos.close();
    }
}


位元組流寫資料+例外處理

  • finally:在例外處理時提供finally塊來執行所有請出操作,比如說IO流中的釋放資源
    • 特點:被finally控制的陳述句一定會執行,除非JVM退出
  • 格式:
try{
    可能出現例外的代碼
}catch(例外類名 變數名){
    例外的處理代碼;
}finally{
    執行所有清除操作;
}

import java.io.FileOutputStream;
import java.io.IOException;
public class Demo {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream("IO流\\fos.txt");
            fos.write("hello".getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fos != null){
                try{
                    fos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

位元組流讀資料

FileInputStream:檔案系統中的獲取輸入位元組

  • int read(),從該輸入流讀取一個位元組的資料
  • int read?(byte[] b) 從該輸入流讀取最多 b.length個位元組的資料到一個位元組陣列,
  • int read?(byte[] b, int off, int len) 從該輸入流讀取最多 len個位元組的資料到位元組陣列,
  • 使用位元組輸入流讀資料的步驟:
    • 創建位元組輸入流物件
    • 呼叫位元組輸入流物件的讀資料方法
    • 釋放資源

位元組緩沖流

  • BufferedOutputStream:該類實作緩沖輸出流,通過設定這樣的輸出流,應用程式可以向底層輸出流寫入位元組,而不必為寫入的每個位元組導致底層系統的呼叫
  • BufferedInputStream:創建BufferedInputStream將創建一個內部緩沖區陣列,當從流中讀取或者跳過位元組時,內部緩沖區將根據需要從所包含的輸入流中重新填充,一次很多位元組,

構造方法

  • 位元組緩沖輸出流:BufferedOutputStream(OutputStream out)
  • 位元組緩沖輸入流:BufferedInputStream(InputStream in)

為什么構造方法需要的是位元組流,而不是具體的檔案或者路徑呢?

  • 位元組緩沖流僅僅提供緩沖區,而真正的讀寫資料還得依靠基本的位元組流物件進行操作,
package 位元組流.位元組緩沖流;

import java.io.*;

/*
 * BufferedOutputStream
 * * BufferedInputStream
 * 構造方法:
 * 位元組緩沖輸出流:BufferedOutputStream(OutputStream out)
 * 位元組緩沖輸入流:BufferedInputStream(InputStream in)
 */
public class Demo {
    public static void main(String[] args) {
        //BufferedOutputStream
/*        BufferedOutputStream bos = null;
    try {
        bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
        bos.write("hello\r\n".getBytes());
        bos.write("world\r\n".getBytes());
    }catch (IOException e){
        e.printStackTrace();
    }finally {
        if (bos != null){
            try {
                bos.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }*/

//BufferedInputStream
        //讀一
/*        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("bos.txt"));
            int len;
           while((len = bis.read()) != -1){
           System.out.print((char)len);
           }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (bis != null){
                try {
                    bis.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }*/
//讀二
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("bos.txt"));
            byte [] b = new byte[1024];
            int len;
            while ((len = bis.read(b)) != -1){
                System.out.print(new String(b,0,len));
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


復制視頻效率對比:


import java.io.*;

public class Demo {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        //緩沖位元組流一次讀取一個位元組
//        method();                         // 50 ms
        //緩沖位元組流一次讀取一個位元組陣列
        method2();                        // 2 ms
        //基本位元組流一次讀取一個位元組陣列
//        method3();                        // 20 ms
        //基本位元組流一次讀取一個位元組
//        method4();                         //  6000 ms
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms");
    }

    //緩沖位元組流一次讀取一個位元組
    public static void method() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("D:\\JAVA\\NBA.qlv"));
            bos = new BufferedOutputStream(new FileOutputStream("D:\\JAVA\\JAVAEE\\NBA.qlv"));
            int len;
            while ((len = bis.read()) != -1) {
                bos.write(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis == null || bos == null) {
                try {
                    bis.close();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //緩沖位元組流一次讀取一個位元組陣列
    public static void method2() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("D:\\JAVA\\NBA.qlv"));
            bos = new BufferedOutputStream(new FileOutputStream("D:\\JAVA\\JAVAEE\\NBA.qlv"));
            byte[] b = new byte[1024];
            int len;
            while ((len = bis.read(b)) != -1) {
                bos.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis == null || bos == null) {
                try {
                    bis.close();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //基本位元組流一次讀取一個位元組陣列
    public static void method3() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\JAVA\\NBA.qlv");
            fos = new FileOutputStream("D:\\JAVA\\JAVAEE\\NBA.qlv");
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                fos.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos == null || fis == null) {
                try {
                    fos.close();
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //基本位元組流一次讀取一個位元組
    public static void method4() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\JAVA\\NBA.qlv");
            fos = new FileOutputStream("D:\\JAVA\\JAVAEE\\NBA.qlv");
            int len;
            while ((len = fis.read()) != -1) {
                fos.write(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos == null || fis == null) {
                try {
                    fos.close();
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


位元組緩沖流效率明顯高于基本位元組流


字符流

為什么會出現字符流

由于位元組流操作中文不是特別方便,所以Java就提供了字符流

  • 字符流 = 位元組流 + 編碼表
    用位元組流復制文本檔案式,文本檔案也會有中文,但是沒問題,是因為最終底層操作會自動進行位元組拼接成中文,如何識別是中文呢?
  • 漢字在存盤的時候,無論選擇哪種編碼存盤,第一個位元組都是負數,

編碼:

  • byte[] getBytes():使用平臺默認字符集將該 String 編碼為一系列位元組,將結果存盤到新的位元組陣列中
  • byte[] getBytes(String charsetName):使用指定的字符集將該 String編碼為一些列位元組,將結果存盤到新的位元組陣列中

解碼:

  • String(byte[] bytes):通過使用平臺的默認字符集解碼指定的位元組陣列來構造新的 String
  • String(byte[] bytes, String charsetName):通過指定的字符集解碼指定的位元組陣列來構造新的String

字符流編碼解碼問題

  • 字符流抽象基類
    • Reader:字符輸入流的抽象類
    • Writer:字符輸出流的抽象類
  • 字符流中和編碼解碼問題相關的兩個類
    • InputStreamReader:是從位元組流到字符流的橋梁:它讀取位元組,并使用指定的charset將其解碼為字符, 它使用的字符集可以由名稱指定,也可以被明確指定,或者可以接受平臺的默認字符集,
    • OutputStreamWriter:是從字符流到位元組流的橋梁:使用指定的charset將寫入的字符編碼為位元組, 它使用的字符集可以由名稱指定,也可以被明確指定,或者可以接受平臺的默認字符集,
import java.io.*;
public class Demo {
    public static void main(String[] args) throws IOException {
        //編碼
//        OutputStreamWriter?(OutputStream out) 創建一個使用默認字符編碼的OutputStreamWriter,
//        OutputStreamWriter?(OutputStream out, String charsetName) 創建一個使用命名字符集的OutputStreamWriter,
        //默認編碼
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"));
        osw.write("中國");
        osw.close();
        //自定義編碼
        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("osw2.txt"), "GBK");
        osw2.write("中華人民共和國");
        osw2.close();
        //解碼
//        InputStreamReader?(InputStream in) 創建一個使用默認字符集的InputStreamReader,
//        InputStreamReader?(InputStream in, String charsetName) 創建一個使用命名字符集的InputStreamReader,
        //默認編碼
        InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"));
        int ch;
        while ((ch = isr.read()) != -1){
            System.out.print((char) ch);
        }
        isr.close();
        System.out.println();
        //自定義編碼
        InputStreamReader isr2 = new InputStreamReader(new FileInputStream("osw2.txt"),"GBK");
        int len;
        char [] c = new char[1024];
        while((len = isr2.read(c)) != -1){
            System.out.println(new String(c,0,len));
        }
        isr2.close();
    }
}

字符流寫資料的5種方式

  • void write(int c) 寫一個字符
  • void write(char[] cbuf)寫入一個字符陣列
  • void write(char[] cbuf, int off, int len)寫入字符陣列的一部分
  • void write(String str)寫一個字串
  • void write(String str, int off, int len)寫入字串的一部分
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Demo {
    public static void main(String[] args) throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"));
        //void write(int c) 寫一個字符
        osw.write(97);
        osw.write(98);

        //void write(char[] cbuf)寫入一個字符陣列
//        char [] c = {'a','b','c','d'};
//        osw.write(c);

        //void write(char[] cbuf, int off, int len)寫入字符陣列的一部分
//        char [] c = {'a','b','c','d'};
//        osw.write(c,1,2);

        //void write(String str)寫一個字串
//        osw.write("hello");

        //void write(String str, int off, int len)寫入字串的一部分
//        osw.write("hello",1,2);

        //void flush()重繪流
        osw.flush();

        osw.close();//關閉流 釋放資源 先重繪 后釋放
    }
}

字符流讀資料的兩種方式

  • int read()一次讀一個字符資料
  • int read(char[] cbuf)一次讀一個字符陣列資料

```import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Demo {
    public static void main(String[] args) throws IOException {
        //int read()一次讀一個字符資料
        InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"));
        int ch;
        while ((ch = isr.read()) != -1){
            System.out.print((char)ch);
        }
        isr.close();
        System.out.println("--------------");

        //int read(char[] cbuf)一次讀一個字符陣列資料
        InputStreamReader isr2 = new InputStreamReader(new FileInputStream("osw.txt"));
        int ch2;
        char [] c = new char[1024];
        while((ch2 = isr2.read(c)) != -1){
            System.out.print(new String(c,0,ch2));
        }
        isr2.close();
    }
}

轉換流的名字較長,而我們常見的操作都是按照本地默認編碼實作的,為了簡便書寫,轉換流提供了對應的子類

  • FileReader:用于讀取取字符的便捷類
    • FileReader(String fileName)
  • FileWriter:用于寫入字符檔案的便捷類
    • FileWriter(String fileName)

字符緩沖流

  • BufferedReader:從字符輸入流讀取文本,緩沖字符,以提供字符,陣列和行的高效讀取, 可以指定緩沖區大小,或者可以使用默認大小, 默認值足夠大,可用于大多數用途,
  • BufferedWriter:將文本寫入字符輸出流,緩沖字符,以提供單個字符,陣列和字串的高效寫入, 可以指定緩沖區大小,或者可以接受默認大小, 默認值足夠大,可用于大多數用途,

構造方法:

  • BufferedReader(Reader in)
  • BufferedWriter(Writer out)
import java.io.*;
public class Demo {
    public static void main(String[] args) throws IOException {
//        BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
//        bw.write("hello\r\n");
//        bw.write("world");
//        bw.close();
        BufferedReader br = new BufferedReader(new FileReader("bw.txt"));
        //一次讀取一個字符資料
//        int len;
//        while((len = br.read()) != -1){
//            System.out.print((char)len);
//        }
        
        //一次讀取一個字符陣列
        int len;
        char [] c = new char[1024];
        while((len = br.read(c)) != -1){
            System.out.print(new String(c,0,len));
        }
        br.close();
    }
}

字符緩沖流特有功能

  • BufferedWriter
    • void newLine():寫一行行分隔符,行分隔符字串由系統屬性定義
  • BufferedReader:
    • public String readLine():讀一行文字,結果包含行的內容的字串,不包括任何行終止符,如果流的結尾已經到達,則為null
import java.io.*;
public class Demo {
    public static void main(String[] args) throws IOException {
   /*     BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
        for (int i = 0; i < 10; i++){
            bw.write("hello"+i);
            bw.newLine();
        }
        bw.close();*/

        BufferedReader br = new BufferedReader(new FileReader("bw.txt"));
        String line;
        while((line = br.readLine()) != null){
            System.out.println(line);
        }
        br.close();
    }
}

JDK7之后的例外處理

格式:

try(定義流物件){
    可能出現例外的代碼;
}catch(例外類 名變數名){
    例外的處理代碼;
}

自動釋放資源

JDK9之后的例外處理

定義輸入流物件;
定義輸出流物件;
try(輸入流物件;輸出流物件){
 可能出現例外的代碼;
}catch(例外類 名變數名){
    例外的處理代碼;
}

自動釋放資源
例如:

package 復制檔案例外加入例外處理;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) {
    }
    
    //JDK9的改進
    private static void method3() throws IOException{
        FileReader fr = new FileReader("fr.txt");
        FileWriter fw = new FileWriter("fw.txt");
        try(fr;fw){
            int len;
            char [] chars = new char[1024];
            while ((len = fr.read(chars)) != -1){
                fw.write(chars,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //JDK7的改進
    private static void method2(){
        try(FileReader fr = new FileReader("fr.txt");
            FileWriter fw = new FileWriter("fw.txt")){
            int len;
            char [] chars = new char[1024];
            while ((len = fr.read(chars)) != -1){
                fw.write(chars,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //try...catch...finally
    private static void method01(){
        FileReader fr = null;
        FileWriter fw = null;
        try{
            fr = new FileReader("fr.txt");
            fw = new FileWriter("fw.txt");
            int len;
            char [] chars = new char[1024];
            while ((len = fr.read(chars)) != -1){
                fw.write(chars,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fr != null){
                try{
                    fr.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        if (fw != null){
            try{
                fw.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}


物件序列化流

物件序列化:就是將物件保存到磁盤中,或網路傳輸物件
這種機制就是使用一個位元組序串列示一個物件,該位元組序列包含:物件的型別、物件的資料和物件的存盤的屬性等資訊位元組序列寫到檔案之后,相當于檔案中保存了一個物件的資訊,反之,該位元組序列還可以從檔案中讀取回來,重構物件,對它進行反序列化

  • 物件序列化流:ObjectOutputStream
  • 物件反序列化流:ObjectInputStream

物件序列化流

ObjectOutputStream將Java物件的原始資料型別和圖形寫入OutputStream, 可以使用ObjectInputStream讀取(重構)物件, 可以通過使用流的檔案來實作物件的持久存盤, 如果流是網路套接字流,則可以在另一個主機上或另一個行程中重構物件,

構造方法:

  • ObjectOutputStream(OutputStream out):創建一個寫入指定的OutputStream的ObjiectOutputStream

序列化物件的方法:

  • void writeObject(Object obj):將指定的物件寫入ObjectOutputStream

注意:物件所屬的類需要實作Serializable介面.不實作此介面將不會使任何狀態序列化或反序列化(僅是一個標識介面,無需要重新的方法)

物件反序列化流

ObjectInputStream反序列化先前使用ObjectOutputStream撰寫的原始資料和物件,

構造方法:

  • ObjectInputStream(InputStream in) 創建從指定的InputStream讀取的ObjectInputStream,

反序列化物件的方法:

  • Object readObject():從ObjectInputStream讀取一個物件
  1. 用 transient 關鍵字修飾的成員變數不會被序列化
  2. 用物件序列流序列化了一個物件后,假如我們修改了物件所屬的類檔案,讀取資料會拋出:InvalidClassException例外.我們可以給物件所屬的類加一個serialVersionUID來解決這個問題,
    private static final long serialVersionUID = 42L;
import java.io.Serializable;

public class Student implements Serializable {
    private static final long serialVersionUID = 42L;
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }
}


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Demo {
    public static void main(String[] args) {
        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"))
            ObjectInputStream ois = new  ObjectInputStream(new FileInputStream("oos.txt"))){

            Student student = new Student("張三",20);

            oos.writeObject(student);

            Object obj = ois.readObject();

            Student s = (Student)obj;

            System.out.println(s.getName() + "," + s.getAge());
            
        }catch (IOException | ClassNotFoundException e){
            e.printStackTrace();
        }
    }
}


Properties

  • 是一個Map體系的集合類
  • Properties可以保存到流中或從流中加載
mport java.util.Properties;
import java.util.Set;


public class Demo {
    public static void main(String[] args) {
        Properties p = new Properties();
        p.put("張三",20);
        p.put("李四",18);
        p.put("王五",19);

        Set<Object> keys = p.keySet();
        for (Object key : keys){
            System.out.println(p.get(key));
        }
    }
}

特有方法:

  • Objiec setProperty(String key,String value) 設值集合的鍵和值,都是String型別,底層呼叫Hashtable方法put
  • String getProperty(String key) 使用此屬性串列中指定的鍵搜索屬性
  • Set stringPropertyNames() 從該屬性串列回傳一個不可修改的鍵集,其中鍵及其對應的值是字串
import java.util.Properties;
import java.util.Set;

public class Demo2 {
    public static void main(String[] args) {
        //Objiec setProperty(String key,String value)
        Properties p = new Properties();
        p.setProperty("張三", "19");
        p.setProperty("李四", "20");
        p.setProperty("王五", "18");
        System.out.println(p);
        System.out.println("--------------");
        //String getProperty(String key)
        String zs = p.getProperty("張三");
        System.out.println(zs);
        System.out.println("--------------");
        //Set<String> stringPropertyNames()
        Set<String> keys = p.stringPropertyNames();
        for (String key : keys) {
            System.out.println(key);
        }

        System.out.println("------------------");
        Set<String> names = p.stringPropertyNames();
        for (String key : names) {
            String values = p.getProperty(key);
            System.out.println(key + "," + values);
        }
    }
}


Properties與IO流

  1. void load(InputStream inStream) 從輸入位元組流讀取屬性串列(鍵和元素對)
  2. void load(Reader reader)從輸入字符流讀取屬性串列(鍵和元素對)
  3. void store(OutputStream out,String comments)將此屬性串列(鍵和元素對)寫入此Properties表中,以適合于使用load(InputStream)方法的格式寫入輸出位元組流
  4. void store(Writer writer, String comments)將此屬性串列(鍵和元素對)寫入此Properties表中,以適合使用load(Reader)方法的格式寫入輸出字符流
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class Demo {
    public static void main(String[] args) throws IOException{
//        mystore();
        myload();
    }


    private static void mystore() throws IOException {
        Properties p = new Properties();
        p.setProperty("張三","20");
        p.setProperty("李四","19");
        p.setProperty("王五","18");
        //void store(OutputStream out,String comments)   comments描述
        FileWriter fw = new FileWriter("IO流\\fw.txt");
        p.store(fw,null);
        fw.close();

    }

    private static void myload() throws IOException{
        Properties p = new Properties();
        FileReader fr = new FileReader("IO流\\fw.txt");
        p.load(fr);
        System.out.println(p);
    }
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/198230.html

標籤:Java

上一篇:年末得到美團/京東/螞蟻金服Java崗內推,分享我的6點面試經驗

下一篇:追蹤將服務器CPU耗光的兇手

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more