最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java中IO流解析及代碼實(shí)例

 更新時(shí)間:2021年07月27日 11:40:32   作者:血蓮丹  
下面小編就為大家?guī)?lái)一篇關(guān)于Java中的IO流總結(jié)(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

I/O簡(jiǎn)介

I/O是Input/output的縮寫(xiě),在java中,對(duì)于數(shù)據(jù)的輸入和輸出以流的方式進(jìn)行。java.io包下提供了各種“流”類和接口,用以獲取不同種類的數(shù)據(jù),并通過(guò)標(biāo)準(zhǔn)的方法輸入或輸出數(shù)據(jù)。 

輸入輸出都是基于內(nèi)存的角度來(lái)說(shuō)的。輸入:讀取外部數(shù)據(jù)(磁盤(pán)、光盤(pán)等存儲(chǔ)設(shè)備的數(shù)據(jù))到程序(內(nèi)存)中。 輸出:輸出output:將程序(內(nèi)存)數(shù)據(jù)輸出到磁盤(pán)、光盤(pán)等存儲(chǔ)設(shè)備中。

流的分類

操作數(shù)據(jù)單位不同分為:字節(jié)流(8 bit),字符流(16 bit)

數(shù)據(jù)流的流向不同分為:輸入流,輸出流

流的角色的不同分為:節(jié)點(diǎn)流,處理流  

節(jié)點(diǎn)流:直接從數(shù)據(jù)源或目的地讀寫(xiě)數(shù)據(jù)。  

處理流:不直接連接到數(shù)據(jù)源或目的地,而是“連接”在已存在的流(節(jié)點(diǎn)流或處理流)之上,通過(guò)對(duì)數(shù)據(jù)的處理為程序提供更為強(qiáng)大的讀寫(xiě)功能。 相當(dāng)于是二次包裝。

抽象基類 字節(jié)流 字符流
輸入流 InputStream Reader
輸出流 OutputStream Writer

Java的IO流共涉及40多個(gè)類,實(shí)際上非常規(guī)則,都是從這4個(gè)抽象基類派生的。由這四個(gè)類派生出來(lái)的子類名稱都是以其父類名作為子類名后綴。

字節(jié)流和字符流常用API

InputStream

  • int read():從輸入流中讀取數(shù)據(jù)的下一個(gè)字節(jié)。返回0到255范圍內(nèi)的int字節(jié)值。如果讀到流的末尾,則返回 -1。 此方法一次只讀一個(gè)字節(jié),效率太低,一般不用
  • int read(byte[] b):從此輸入流中將最多b.length個(gè)字節(jié)的數(shù)據(jù)保存到一個(gè)byte數(shù)組中。返回實(shí)際讀取字節(jié)長(zhǎng)度,如果讀到流的末尾,也返回 -1。
  • int read(byte[] b,int off,int len):將輸入流中最多l(xiāng)en個(gè)數(shù)據(jù)字節(jié)讀入byte數(shù)組。嘗試讀取len個(gè)字節(jié),但讀取的字節(jié)也可能小于該值,實(shí)際讀取個(gè)數(shù)以讀取到的為準(zhǔn),比如長(zhǎng)度為23個(gè)字節(jié)的內(nèi)容,每次讀取5個(gè)字節(jié),則第五次讀取流并沒(méi)處于末尾,還剩長(zhǎng)度是3,故返回3。第六次讀取發(fā)現(xiàn)是末尾,則返回 -1 。一般都用此方法。
  • public void close() throws IOException:關(guān)閉此輸入流并釋放與該流關(guān)聯(lián)的所有系統(tǒng)資源,一定要關(guān)閉。

Reader

  • Reader和InputStream類似,就是將字節(jié)數(shù)組換成了字符數(shù)組
  • int read(); 效果與字節(jié)流一致
  • int read(char[] cbuf); 效果與字節(jié)流一致
  • int read(char[] cbuf,int off,int len); 效果與字節(jié)流一致
  • public void close() throws IOException;關(guān)閉此輸入流并釋放與該流關(guān)聯(lián)的所有系統(tǒng)資源,字符流的必須要關(guān)閉,不然會(huì)出問(wèn)題

OutputStream

  • void write(int b) :將指定的字節(jié)寫(xiě)入此輸出流。
  • void write( byte[] b) :將b.length個(gè)字節(jié)從指定的byte數(shù)組寫(xiě)入此輸出流。
  • void write(byte[] b,int off,int len):將指定byte數(shù)組中從偏移量off開(kāi)始的len個(gè)字節(jié)寫(xiě)入此輸出流。
  • public void flush() throws IOException:刷新此輸出流并強(qiáng)制寫(xiě)出所有緩沖的輸出字節(jié),調(diào)用此方法指示應(yīng)將這些字節(jié)立即寫(xiě)入它們預(yù)期的目標(biāo)。就是將緩沖的字節(jié)全部寫(xiě)出到字節(jié)或字符數(shù)組中。
  • public void close() throws IOException:關(guān)閉此輸入流并釋放與該流關(guān)聯(lián)的所有系統(tǒng)資源

Writer

  • void write(int c):寫(xiě)入單個(gè)字符。
  • void write(char[] cbuf):寫(xiě)入字符數(shù)組。
  • void write(char[] cbuf,int off,int len) : 寫(xiě)入字符數(shù)組的某一部分。從off開(kāi)始,寫(xiě)入len個(gè)字符
  • void write(String str):寫(xiě)入字符串。
  • void write(String str,int off,int len):寫(xiě)入字符串的某一部分。
  • void flush():刷新該流的緩沖,則立即將它們寫(xiě)入預(yù)期目標(biāo)。
  • public void close() throws IOException:關(guān)閉此輸入流并釋放與該流關(guān)聯(lián)的所有系統(tǒng)資源

字節(jié)字符流相關(guān)操作

字節(jié)流讀取文本內(nèi)容

// 讀取文本文件內(nèi)容,用字節(jié)流去讀,可能會(huì)亂碼
    public void test1() {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("hello.txt");//相對(duì)路徑是工程路徑下
            int len;
            byte[] bytes = new byte[5];// 定義5字節(jié)長(zhǎng)度的byte數(shù)組
            while ((len = inputStream.read(bytes)) != -1) {// 將數(shù)據(jù)讀到byte數(shù)組中
                System.out.println(new String(bytes, 0, len)); //打印到控制臺(tái)
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}

字符流讀取文本內(nèi)容

// 讀取文本文件內(nèi)容,用字符流去讀,不會(huì)亂碼,最多重復(fù)	
    public void test2() {
        Reader reader = null;
        try {
            reader = new FileReader("hello.txt");
            int len;
            char[] charBuff = new char[5];
            while ((len = reader.read(charBuff)) != -1) {
//                System.out.println(new String(charBuff)); // 注意這兩行的代碼區(qū)別
                System.out.println(new String(charBuff, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

字節(jié)流讀取文件到輸出到指定位置

public void test3() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream("hello.txt"); // 讀取文件
            outputStream = new FileOutputStream("hello2.txt"); // 相對(duì)路徑,默認(rèn)是工程路徑下
            int len;
            byte[] bytes = new byte[5];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

字符流讀取文件到輸出到指定位置

字符流讀取文件到輸出到指定位置時(shí),如果沒(méi)有手動(dòng)關(guān)閉流,則不會(huì)輸出到指定位置,需要手動(dòng)flush。但是如果在finally塊中關(guān)閉了流,則會(huì)自動(dòng)flush。在close()操作中,會(huì)幫我們flush。

public void test4() {
        Reader reader = null;
        Writer writer = null;
        try {
            reader = new FileReader("hello2.txt");
            writer = new FileWriter("hello3.txt");
            int len;
            char[] charBuff = new char[5];
            while ((len = reader.read(charBuff)) != -1) {
                writer.write(charBuff, 0, len);
//                writer.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) { // 一定要關(guān)閉字符流,否則要手動(dòng)flush
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

注意,字符流用來(lái)處理字符串很便捷,并且只能操作普通的文本文件,例如:.txt,.java,.c,.cpp 等語(yǔ)言的源代碼。尤其注意.doc,excel,ppt這些不是文本文件。字節(jié)流既可以操做文本文件,也可以操作字節(jié)文件,比如.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt。如果用字符流來(lái)操作圖片等字節(jié)文件,生成的文件是無(wú)法打開(kāi)的!

緩沖流

為了提高數(shù)據(jù)讀寫(xiě)的速度,Java API提供了帶緩沖功能的流類,在使用這些流類時(shí),會(huì)創(chuàng)建一個(gè)內(nèi)部緩沖區(qū)數(shù)組,缺省使用 8192個(gè)字節(jié)(8Kb) 的緩沖區(qū)。

緩沖流要“套接”在相應(yīng)的節(jié)點(diǎn)流之上,根據(jù)數(shù)據(jù)操作單位可以把緩沖流分為BufferedInputStream和ufferedOutputStream以及BufferedReader和BufferedWriter。分別對(duì)應(yīng)字節(jié)緩沖流和字符緩沖流。相當(dāng)于在字節(jié)和字符流上包裝了一下。

BufferedInputStream和BufferedOutputStream

public void test() {
        InputStream inputStream ;
        OutputStream outputStream ;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            inputStream = new FileInputStream("modify.txt"); //小于8KB
            outputStream = new FileOutputStream("modify2.txt");
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(outputStream);
            int len;
            byte[] bytes = new byte[5];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

BufferedReader和BufferedWriter

public void test2() {
        Reader reader ;
        Writer writer ;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            reader = new FileReader("modify.txt");
            writer = new FileWriter("modify2.txt");
            br = new BufferedReader(reader);
            bw = new BufferedWriter(writer);
            int len;
            char[] bytes = new char[5];
            while ((len = br.read(bytes)) != -1) {
                bw.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (bw != null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

**緩沖流如果沒(méi)有手動(dòng)關(guān)閉流,且讀取的文件小于底層緩存大小8KB,是不會(huì)自動(dòng)寫(xiě)到目標(biāo)中去的,需要手動(dòng)flush。**在關(guān)閉流時(shí),只需關(guān)閉緩沖流即可,它會(huì)自動(dòng)關(guān)閉它包裝的底層節(jié)點(diǎn)流。

數(shù)據(jù)流

為了方便地操作Java語(yǔ)言的基本數(shù)據(jù)類型和String的數(shù)據(jù),可以使用數(shù)據(jù)流。數(shù)據(jù)流有兩個(gè)類:DataInputStream和DataOutputStream, 別“套接”在InputStream和OutputStream子類的流上。

使用如下:

 public void test() {
        DataOutputStream dos = null;
        try {
            OutputStream outputStream = new FileOutputStream("data.txt");
            dos = new DataOutputStream(outputStream);
            dos.writeUTF("熱烈慶祝中國(guó)共產(chǎn)黨成立一百周年");
            dos.writeInt(100);
            dos.writeBoolean(true);
            System.out.println("成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void test2(){
        DataInputStream dis =  null;
        try {
            InputStream inputStream = new FileInputStream("data.txt");
            dis = new DataInputStream(inputStream);
            System.out.println(dis.readUTF()); //讀取時(shí)要按照寫(xiě)入順序讀取
            System.out.println(dis.readInt());
            System.out.println(dis.readBoolean());
            System.out.println("成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dis != null) {
                    dis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

對(duì)象流

用于存儲(chǔ)和讀取基本數(shù)據(jù)類型數(shù)據(jù)或?qū)ο蟮奶幚砹鳌?strong>它的強(qiáng)大之處就是可以把Java中的對(duì)象寫(xiě)入到數(shù)據(jù)源中,也能把對(duì)象從數(shù)據(jù)源中還原回來(lái)。

  • 序列化:用ObjectOutputStream類保存基本類型數(shù)據(jù)或?qū)ο蟮臋C(jī)制
  • 反序列化:用ObjectInputStream類讀取基本類型數(shù)據(jù)或?qū)ο蟮臋C(jī)制
  • ObjectOutputStream和ObjectInputStream不能序列化static和transient修飾的成員變量

序列化與反序列化的演示

先定義一個(gè)Person類,該類必須實(shí)現(xiàn)Serializable接口,否則序列化時(shí)會(huì)報(bào)java.io.NotSerializableException 的錯(cuò)誤

package day07;
import java.io.Serializable;
import java.util.Date;
public class Person implements Serializable {
    private static final long serialVersionUID = -5858950242987134591L;
    private String name;
    private Integer age;
    private Date date;
    public Person(){}
    public Person(String name, Integer age, Date date) {
        this.name = name;
        this.age = age;
        this.date = date;
    }
  // getter、setter略
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", date=" + date +
                '}';
    }
}

序列化

    public void test() {
        ObjectOutputStream oos = null;
        try {
            OutputStream outputStream = new FileOutputStream("person.txt"); // 創(chuàng)建輸出流對(duì)象,指定輸出位置
            oos = new ObjectOutputStream(outputStream); // 包裝輸出流
            oos.writeObject(new Person("張三",22,new Date())); // 序列化對(duì)象
            System.out.println("序列化成功!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

反序列化

public void test2() {
        ObjectInputStream ois = null;
        try {
            InputStream inputStream = new FileInputStream("person.txt");
            ois = new ObjectInputStream(inputStream);
            Person person = (Person) ois.readObject();
            System.out.println("person姓名為:" + person.getName());
            System.out.println("person年齡為:" + person.getAge());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh時(shí)mm分ss秒");
            System.out.println("創(chuàng)建時(shí)間為:" + sdf.format(person.getDate()));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

在這里插入圖片描述

無(wú)論如何反序列化,時(shí)間都是不變的。

總結(jié)

本篇文章就到這里了,希望能給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

  • Java多線程產(chǎn)生死鎖的必要條件

    Java多線程產(chǎn)生死鎖的必要條件

    今天小編就為大家分享一篇關(guān)于Java多線程產(chǎn)生死鎖的必要條件,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • Java 詳解包裝類Integer與int有哪些共通和不同

    Java 詳解包裝類Integer與int有哪些共通和不同

    這篇文章主要介紹的是 Java中int和Integer的區(qū)別,Java 是一種強(qiáng)數(shù)據(jù)類型的語(yǔ)言,因此所有的屬性必須有一個(gè)數(shù)據(jù)類型,下面文章基于Java詳細(xì)int和Integer有何區(qū)別,需要的朋友可以參考一下
    2022-04-04
  • Spring Boot如何防止重復(fù)提交

    Spring Boot如何防止重復(fù)提交

    這篇文章主要為大家詳細(xì)介紹了Spring Boot如何防止重復(fù)提交,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • 關(guān)于java入門(mén)與java開(kāi)發(fā)環(huán)境配置詳細(xì)教程

    關(guān)于java入門(mén)與java開(kāi)發(fā)環(huán)境配置詳細(xì)教程

    這篇文章主要介紹了關(guān)于java入門(mén)與java開(kāi)發(fā)環(huán)境配置詳細(xì)教程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • Java多線程--讓主線程等待所有子線程執(zhí)行完畢在執(zhí)行

    Java多線程--讓主線程等待所有子線程執(zhí)行完畢在執(zhí)行

    Java主線程等待所有子線程執(zhí)行完畢在執(zhí)行,其實(shí)在我們的工作中經(jīng)常的用到,本篇文章就介紹了Java多線程--讓主線程等待所有子線程執(zhí)行完畢在執(zhí)行,有需要的可以了解一下。
    2016-11-11
  • Java讀取傳輸FTP文件實(shí)現(xiàn)示例

    Java讀取傳輸FTP文件實(shí)現(xiàn)示例

    本文主要介紹了Java讀取傳輸FTP文件方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Eclipse快速添加get、set方法的操作技巧

    Eclipse快速添加get、set方法的操作技巧

    這篇文章主要介紹了Eclipse快速添加get、set方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-07-07
  • 解決Java中socket使用getInputStream()阻塞問(wèn)題

    解決Java中socket使用getInputStream()阻塞問(wèn)題

    這篇文章主要介紹了解決Java中socket使用getInputStream()阻塞問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot應(yīng)用監(jiān)控Actuator使用隱患及解決方案

    SpringBoot應(yīng)用監(jiān)控Actuator使用隱患及解決方案

    SpringBoot的Actuator 模塊提供了生產(chǎn)級(jí)別的功能,比如健康檢查,審計(jì),指標(biāo)收集,HTTP 跟蹤等,幫助我們監(jiān)控和管理Spring Boot 應(yīng)用,本文將給大家介紹SpringBoot應(yīng)用監(jiān)控Actuator使用隱患及解決方案,需要的朋友可以參考下
    2024-07-07
  • pom.xml中解決Provides?transitive?vulnerable?dependency?maven:org.yaml:snakeyaml:1.33警告問(wèn)題

    pom.xml中解決Provides?transitive?vulnerable?dependency?mave

    這篇文章主要介紹了在pom.xml中如何解決Provides?transitive?vulnerable?dependency?maven:org.yaml:snakeyaml:1.33警告問(wèn)題,需要的朋友可以參考下
    2023-06-06

最新評(píng)論

交城县| 蒙城县| 新乐市| 邹城市| 房产| 汶上县| 沙湾县| 维西| 大邑县| 广水市| 同心县| 法库县| 赞皇县| 内黄县| 疏附县| 乐都县| 凌源市| 山阴县| 威海市| 淳化县| 两当县| 祁连县| 庄浪县| 罗城| 霍山县| 比如县| 孟州市| 昂仁县| 孝昌县| 东辽县| 苏尼特右旗| 黑河市| 伊春市| 连云港市| 白沙| 万安县| 遂昌县| 吉木萨尔县| 绥化市| 河北省| 宁海县|