1. 程式人生 > 其它 >IO--輸入輸出流和字元流

IO--輸入輸出流和字元流

IO--輸入輸出流和字元流

輸入及輸出

•輸入輸出(I/O)

把電腦硬碟上的資料讀到程式中,稱為輸入,即input,進行資料的read操作

從程式往外部裝置寫資料,稱為輸出,即output,進行資料的write操作

•InputStream和OutputStream的子類都是位元組流

-可以讀寫二進位制檔案,主要處理音訊、圖片、歌曲、位元組流,處理單元為1個位元組。

•Reader和Writer的子類都是字元流

​ 主要處理字元或字串,字元流處理單元為1個字元。

​ 位元組流將讀取到的位元組資料,去指定的編碼表中獲取對應文字。

public static void main(String[] args) {
        try {
            //建立FileInputStream的物件,指定要輸入(讀)的檔案,檔案不存在,丟擲異常
            FileInputStream in = new FileInputStream("E:\\demo.txt");
            //每次read();一次,從輸入流中讀到一個位元組,當讀取完後會返回-1
            int b = in.read();
            System.out.println(b);
            int b1 = in.read();
            System.out.println(b1);
            int b2 = in.read();
            System.out.println(b2);
            int b3 = in.read();
            System.out.println(b3);
            int b4 = in.read();
            System.out.println(b4);
            int b5 = in.read();
            System.out.println(b5);
            int b6 = in.read();
            System.out.println(b6);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

輸入輸出成對出現

  public static void main(String[] args) {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            /*
            建立FileInputStream物件,指定要輸入(讀)的檔案,檔案不存在,會丟擲異常
             */
            in = new FileInputStream("E:\\demo.txt");
            /*
            建立FileOutputStream物件,會自動建立輸出的檔案
             */
            out = new FileOutputStream("F:\\demo.txt");
            int b = 0;
            while ((b = in.read()) != -1) {
                System.out.println(b);
                out.write(b);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //關閉流物件,釋放系統資源
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

有效程式碼

    public static void main(String[] args) throws IOException {
            /*
            建立FileInputStream物件,指定要輸入(讀)的檔案,檔案不存在,會丟擲異常
             */
        FileInputStream in = new FileInputStream("E:\\demo.txt");
            /*
            建立FileOutputStream物件,會自動建立輸出的檔案
             */
        FileOutputStream out = new FileOutputStream("F:\\demo.txt");
        int b = 0;
        while ((b = in.read()) != -1) {
            System.out.println(b);
            out.write(b);
        }
        in.close();
        out.close();
    }

讀寫效率的提升

package com.ff.javaio.Day2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class StreamDemo3 {
    public static void main(String[] args) throws IOException {
            /*
            建立FileInputStream物件,指定要輸入(讀)的檔案,檔案不存在,會丟擲異常
             */
        FileInputStream in = new FileInputStream("E:\\demo.txt");
            /*
            建立FileOutputStream物件,會自動建立輸出的檔案
             */
        FileOutputStream out = new FileOutputStream("F:\\demo.txt");
        /*
        read();每次從輸入流中讀取一個字元  返回字元值  讀完返回-1
        read(byte[] b)每次從輸入流中讀取一個byte陣列長度個字元,返回陣列中實際裝入內容個數,讀完返回-1
         */
        byte [] b = new byte[10];
        int length=0;
        while((length=in.read(b))!=-1){
           /* out.write(b);每次傳10個字元,不足10個字元,會自動填充空格*/
            out.write(b,0,length);//向外寫出一個byte陣列個位元組,從陣列指定位置開始,寫length個位元組
        }
        in.read(b);
        in.close();
        out.close();
    }
}

緩衝位元組輸入/出流

public static void main(String[] args) throws IOException {
        //建立輸入節點流,負責對檔案讀寫
        FileInputStream in = new FileInputStream("D:\\Users\\17509\\Desktop\\Tule - Fearless.mp3");
        //建立處理物件,內部有一個緩衝陣列,預設為8192個位元組,包裝輸入流,提供緩衝功能,也可以設定緩衝區大小
        BufferedInputStream bin = new BufferedInputStream(in);

        FileOutputStream out = new FileOutputStream("E:/新建檔案.mp3");
        BufferedOutputStream bout = new BufferedOutputStream(out);

       /* int b= 0;
        while ((b=bin.read())!=-1){
            bout.write(b);
        }*/
        int length = 0;
        byte[] b = new byte[1024];
        while ((length = bin.read(b)) != -1) {
            bout.write(b, 0, length);
        }
        bout.flush();//重新整理緩衝區
        bout.close();
        bin.close();
    }

字元流

  字元流,以字元為單位讀寫資料
        Reader
            轉換流  InpuStreamReader
            FileReader
            BufferedReader
          Writer
            轉換流         OutStreamWriter
            FileWriter
            BufferedWriter

Reader 的基本方法 讀取一個字元並以整數的形式返回, 如果返回-1已到輸入流的末尾。
Writer 的基本方法向輸出流中寫入一個字元資料,該位元組資料為引數b的16位

FileReader&&FileWriter

 public static void main(String[] args) throws IOException {
    
        FileReader reader = new FileReader("D:\\test.txt");
        FileWriter writer = new FileWriter("D:\\test1.txt");
        /*int c = ' ';
        while((c= reader.read())!=-1){
            System.out.println((char)c);
            writer.write(c);
        }*/
        //讀取為字元型別陣列
        char[] c = new char[5];
        int length;
        while((length= reader.read(c))!=-1){
            System.out.println(length);
            writer.write(c,0,length);
        }
        writer.close();
        reader.close();
    }

BufferedReader&&BufferedWriter

FileWriter方法中有字元拼接,寫入時不會覆蓋原來的內容,會在後面繼續拼接
BufferedWriter中readLine();方法,實現了每次可以讀取檔案中一行的功能

 public static void main(String[] args) throws IOException {
        FileReader reader = new FileReader("D:\\test.txt");
        BufferedReader breader = new BufferedReader(reader);

        // FileWriter方法中有字元拼接,寫入時不會覆蓋原來的內容,會在後面繼續拼接
        FileWriter writer = new FileWriter("D:\\test1.txt", true);
        BufferedWriter bwriter = new BufferedWriter(writer);

        //讀完時返回null;
        //breader.readLine()一次讀一行資料
        /*System.out.println(breader.readLine());
        System.out.println(breader.readLine());
        System.out.println(breader.readLine());*/

        String line = null;
        while ((line = breader.readLine()) != null) {
            bwriter.write(line);//一次一行寫入
            bwriter.newLine();//新的一行
        }
        bwriter.flush();
        bwriter.close();
        breader.close();
    }

Print列印流

列印流:單向的從程式中向外輸出資料
PrintWriter:列印字元流
案例: 例如 從伺服器端向 客戶端瀏覽器 輸出網頁資訊.

 public static void main(String[] args) throws FileNotFoundException {
        
        PrintWriter  out = new PrintWriter("E:\\demo.html");
        out.println("<h1>這是從伺服器端響應回來的資料</h1>");
        out.println("<h1>這是從伺服器端響應回來的資料</h1>");
        out.write("<h2>這是從伺服器端響應回來的資料</h2>");
        out.print(true);// print底層使用的還是write()  只是過載了多個,可以處理多種的資料型別
		out.close();
    }

物件輸入輸出流(物件序列化和反序列化)

物件輸入輸出流
物件:記憶體中的物件
為什麼要將物件輸出?
記憶體中的資料在電腦關閉,伺服器停止時資料就會消失
有時候需要將這些資料儲存起來

物件的輸出流: ObjectOutputStream  
物件的輸入流: ObjectInputStream

 public static void main(String[] args) throws IOException, ClassNotFoundException {
// 物件的序列化
		FileOutputStream out = new FileOutputStream("D:\\demo.txt");
		
		//ObjectOutputStream中用writeObject()方法可以直接將物件儲存到輸出流中。
        ObjectOutputStream oout = new ObjectOutputStream(out);

        String s ="abc";
        Date date =new Date();

        oout.writeObject(s);
        oout.writeObject(date);
        oout.close();

		//反序列化
        FileInputStream in = new FileInputStream("D:\\demo.txt");
        
        //在ObjectInputStream 中用readObject()方法可以直接讀取一個物件
        ObjectInputStream oin =new ObjectInputStream(in);
        String s =(String) oin.readObject();
        Date date = new Date();
        System.out.println(s);
        System.out.println(date);
        oin.close();
    }

新建Student類

/*
需要被序列化類的物件,此類必須要實現Serializable介面
 */
public class Student implements Serializable {
    //會自動為類生成一個 預設ID號,當此類中的內容發生修改後,id號會發生變化
    //實用工具生成一個序列化ID號,這樣類發生修改後,此ID依然不會改變
    private static final long serialVersionUID = -7119195593092378008L;
    int num;
    String name;
    //被transient修飾的屬性,不能被序列化
    transient String adress;

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

    @Override
    public String toString() {
        return "Student{" +
                "num=" + num +
                ", name='" + name + ",adress="+adress+'\'' +
                '}';
    }
}

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileOutputStream fos = new FileOutputStream("D:\\demo.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        Student stu = new Student(12,"jim","陝西省");
        oos.writeObject(stu);
        oos.close();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileInputStream in = new FileInputStream("D:\\demo.txt");
        ObjectInputStream oin = new ObjectInputStream(in);
        Student student = (Student)oin.readObject();
        System.out.println(student);
        oin.close();
    }