JavaSEday11字節流和字符流

day11_面對對象(字節流、字符流)
    一.字節流
        4.字節輸入流InputStream
            字節輸入流的頂層父類:InputStream(抽象類)
            共性方法:
                public int read(); 一次讀取一個字節
                public int read(byte[] bs); 一次讀取一個字節數組,  返回值表示實際讀取的長度
                
                public void close(); 釋放資源
        5.FileInputStream類的使用(文件的字節輸入流)
            a.構造方法
                public FileInputStream(String pathname);
                public FileInputStream(File file);

public class FileInputStreamDemo01 {
    public static void main(String[] args) throws FileNotFoundException {
        //1.創建一個FileInputStream對象
        FileInputStream fis = new FileInputStream("1.txt");
//        FileInputStream fis = new FileInputStream(new File("1.txt"));
        /**
         * 以上構造幹了三件事!!!
         * a.創建對象fis
         * b.判斷文件是否存在
         *      如果存在,不清空
         *      如果不存在,會拋出FileNotFoundException文件找不到異常
         * c.讓fis對象和1.txt綁定
         */
    }
}

            b.讀取一個字節**********************

public class FileInputStreamDemo02 {
    public static void main(String[] args) throws IOException {
        //1.創建一個FileInputStream對象
        FileInputStream fis = new FileInputStream("1.txt");
        //2.讀數據
        //一次讀取單個字節
//        int b = fis.read();
//        System.out.println((char) b);
        //一次讀取一個字節的標準循環代碼
        int b = 0;//用來保存讀取到字節
        /**
         * (b = fis.read()) != -1
         * 以上代碼幹了三件事!!!
         * a.先讀   fis.read()
         * b.賦值   b = 讀取到的字節
         * c.判斷   b != -1  
         */
        while ((b = fis.read()) != -1) {
            System.out.println((char)b);
        }

        //3.釋放資源
        fis.close();
    }
}

                
            c.讀取一個字節數組*********************

public class FileInputStreamDemo03 {
    public static void main(String[] args) throws IOException {
        //1.創建一個FileInputStream對象
        FileInputStream fis = new FileInputStream("1.txt");
        //2.讀數據
        //一次讀取一個字節數組的標準循環代碼
        int len = 0;//保存實際讀取的字節個數
        byte[] bs = new byte[4];//保存字節的數組
        /**
         * (len = fis.read(bs)) != -1
         * 以上代碼三個三件事!!
         * a.先讀  fis.read(bs)
         * b.賦值  len = 實際讀取的個數
         * c.判斷  len != -1
         */
        while ((len = fis.read(bs)) != -1) {
            System.out.print(new String(bs,0,len));
        }
        //3.釋放資源
        fis.close();
    }
}

        6.字節流練習:複製圖片**********************
            a.複製文件的過程(畫圖)
            b.代碼實現(代碼演示)

public class CopyFileDemo {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        copy02();
        long end = System.currentTimeMillis();
        System.out.println("耗時:" + (end - start) + "毫秒");
    }

    //一次複製一個字節
    //耗時:37709毫秒
    public static void copy01() throws Exception {
        //1.創建文件的輸入流
        FileInputStream fis = new FileInputStream("G:\\upload\\1.png");
        //2.創建文件的輸出流
        FileOutputStream fos = new FileOutputStream("copy.png");
        //3.複製
        //一次讀一個字節 寫一個字節
        int b = 0;//保存讀取到的字節
        while ((b = fis.read()) != -1) {
            fos.write(b);
        }
        //4.釋放資源
        fos.close();
        fis.close();
    }


    //一次複製一個字節數組
    //耗時:20毫秒
    public static void copy02() throws Exception {
        //1.創建文件的輸入流
        FileInputStream fis = new FileInputStream("G:\\upload\\1.png");
        //2.創建文件的輸出流
        FileOutputStream fos = new FileOutputStream("copy.png");
        //3.複製
        //一次讀取一個字節數組 寫出一個字節數組
        int len = 0;
        byte[] bs = new byte[1024 * 8];
        while ((len = fis.read(bs)) != -1) {
            fos.write(bs, 0, len);
        }
        //4.釋放資源
        fos.close();
        fis.close();
    }
}


    二.字符流
        1.爲什麼要用字符流
            因爲中文或者其他文字,一箇中文是由2-3字節組成的
            如果我們使用字節流,很可能出現一種情況,讀取文字時只讀取一部分字節

public class WhyDemo {
    public static void main(String[] args) throws IOException {
    //        爲什麼要用字符流
    //        因爲中文或者其他文字,一箇中文是由2-3字節組成的
    //                如果我們使用字節流,很可能出現一種情況,讀取中文時只讀取一部分字節
                //文件中的內容是:a中b國c萬d歲e
                    FileInputStream fis = new FileInputStream("1.txt");
                    //讀取
                    int b = fis.read();
                    System.out.println((char) b); //a

                   b = fis.read();
                    System.out.println((char) b);//中的一半 亂碼

                    b = fis.read();
                    System.out.println((char) b);//中的另一半 亂碼

                    b = fis.read();
                    System.out.println((char) b);//b

                    fis.close();

                    }
            }

        2.字符輸入流
            字符輸入流頂層父類:Reader(抽象類)
            共性方法:
                public int read(); 一次讀取一個字符
                public int read(char[] chs); 一次讀取一個字符數組,返回值表示實際讀取的個數
                public void clsoe(); 釋放資源

        3.FileReader類的使用
            文件的字符輸入流
            a.構造方法
                public FileReader(String pathname);
                public FileReader(File file);

public class FileReaderDemo01 { 
    public static void main(String[] args) throws Exception {
        //1.創建FileReader
        FileReader fr = new FileReader("1.txt");
//        FileReader fr = new FileReader(new File("1.txt"));
        /**
         * 以上構造幹了三件事i!!
         * a.創建對象fr
         * b.判斷文件是否存在
         *          如果存在,不清空
         *          如果不存在,直接拋出FileNotFoundException
         * c.綁定fr和1.txt文件
         */
    }
}

            b.讀取一個字符**********************

public class FileReaderDemo02 {
    public static void main(String[] args) throws Exception {
        //1.創建FileReader
        FileReader fr = new FileReader("1.txt");
        //2.讀字符數據
        //一次讀取單個字符
//        int ch = fr.read();
//        System.out.println((char) ch);
        //一次讀取一個字符的標準循環
        int ch = 0;//保存讀取到的字符
        /**
         * (ch = fr.read()) != -1
         * a.先讀 fr.read()
         * b.賦值 ch = 讀取到的字符
         * c.判斷 ch != -1
         */
        while ((ch = fr.read()) != -1) {
            System.out.print((char) ch);
        }
        
        //3.釋放資源
        fr.close();
    }
}

            c.讀取一個字符數組****************

public class FileReaderDemo03 {
    public static void main(String[] args) throws Exception {
        //1.創建FileReader
        FileReader fr = new FileReader("1.txt");
        //2.讀字符數據
        //一次讀取一個字符數組的標準循環代碼
        int len = 0;//用來保存實際讀取的字符個數
        char[] chs = new char[4];//保存讀取的字符數組
        /**
         * (len = fr.read(chs)) != -1
         * a.先讀 fr.read(chs)
         * b.賦值 len = 實際讀取的字符個數
         * c.判斷 len != -1
         */
        while ((len = fr.read(chs)) != -1) {
            System.out.print(new String(chs, 0, len));
        }
        //3.釋放資源
        fr.close();
    }
}

        4.字符輸出流
            字符輸出流頂層父類:Writer(抽象類)
            共性方法:
                public void write(int ch); 一次寫一個字符
                public void write(char[] chs); 一次寫一個字符數組
                public void write(char[] chs. int startIndex, int  len); 一次寫一個字符數組一部分

                public void write(String str); 一次寫一個字符串
                public void write(String str, int startIndex, int len); 一次寫一個字符串的一部分

                public void flush(); 刷新緩衝區(對於字符輸出流來說是有用的!!!將緩衝區裏的內容寫進文件再進行刷新但流不關                閉)
                public void close(); 釋放資源
        5.FileWriter類的使用
            文件的字符輸出流
            a.構造方法
                public FileWriter(String name);
                public FileWriter(File file);

public class FileWriterDemo01 {
    public static void main(String[] args) throws IOException {
        //1.創建FileWriter對象
        FileWriter fw = new FileWriter("2.txt");
//        FileWriter fw = new FileWriter(new File(""));
        /**
         * 以上構造幹了三件事
         * a.創建對象fw
         * b.判斷文件是否存在
         *      如果存在,清空文件內容
         *      如果不存在,自動創建
         * c.綁定fw和2.txt
         */
    }
}

            b.寫出字符數據的三組方法
                public void write(int ch); 一次寫一個字符
                public void write(char[] chs); 一次寫一個字符數組
                public void write(char[] chs, int startIndex, int len); 一次寫一個字符數組的一部分

                public void write(String str); 一次寫一個字符串
                public void write(String str, int startIndex, int len); 一次寫一個字符串的一部分

public class FileWriterDemo02 {
    public static void main(String[] args) throws IOException {
        //1.創建FileWriter對象
        FileWriter fw = new FileWriter("2.txt");
        //2.寫字符數組的三組方法
        //a.寫一個字符
        fw.write('a');
        fw.write('中');
        //b.寫一個字符數組(一部分)
        char[] chs = {'中', '國', '我', '愛', '你'};
        fw.write(chs);
        fw.write(chs,2,3);
        //c.寫一個字符串(一部分)
        fw.write("Java我愛你");
        fw.write("Java我愛你", 3, 3);
        //3.釋放資源
        fw.close();
    }
}

            c.關閉和刷新的區別
                flush():將緩衝區數據刷到目標文件中,flush之後流依然可以繼續使用
                close():先flush,後釋放資源,close之後流已經關閉不能再繼續使用

public class FileWriterDemo03 {
    public static void main(String[] args) throws IOException {
        //1.創建FileWriter對象
        FileWriter fw = new FileWriter("2.txt");
        //2.flush方法,刷新緩衝區
        fw.write("phpphp");
        fw.flush();//刷新緩衝區

        fw.write("javajava"); //flush之後流沒有關閉,可以繼續使用
        fw.flush(); //刷新緩衝區
        //3.釋放資源
        fw.close();
    //fw.write("java"); //close之後流已經關閉不能繼續使用
    }
}

            d.續寫和換行
                i.每次創建FileWriter對象文件都會清空,如何續寫呢?
                    要使用下面構造即可
                    public FileWriter(String pathname, boolean append);
                    public FileWriter(File file, boolean append);
                ii.如何換行
                    只要向文件中寫一個換行符即可
                    windows --> "\r\n"
                    Linux --> "\n"
                    Mac --> "\r" (Max OS X之後用"\n")

public class FileWriterDemo04 {
    public static void main(String[] args) throws IOException {
        //1.創建FileWriter對象
        FileWriter fw = new FileWriter("2.txt");
        //2.換行
        for (int i = 0; i < 10; i++) {
            fw.write("php\r\n");
//            fw.write("\r\n");
        }
        //3.釋放資源
        fw.close();
    }
}

                    
    三.IO流的異常處理
        1.JDK7之前的標準IO處理

/**
     * JDK1.7引入新的IO流異常處理機制
     *      try-with-resource
     */
    public static void method02() {
        try (FileReader fr = new FileReader("2.txt")) {
            int read = fr.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

        2.JDK7引入的try-with-resource處理

/**
* JDK1.7之前的標準IO流異常處理代碼
*/
public static void method01(){
        //1.創建FileReader
        FileReader fr = null;
        try {
            fr = new FileReader("2.txt");
            int read = fr.read();

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


    四.Properties類****************
        1.Properties類的介紹
            Prperties類表示一個持久的屬性集
            屬性集:本質上就是Map集合,Properties已經確定鍵和值的具體類型
            持久的:Properties可以有方法直接把數據保存到硬盤的某個文件中
        2.構造方法
            public Properties(); 創建一個空的屬性集

        3.基本保存數據的方法

public static void main(String[] args) {
    //1.創建一個Properties對象
    Properties ps = new Properties();
    System.out.println(ps);
    //2.添加
    ps.setProperty("username","root");//相當於Map的put方法
    ps.setProperty("password","1234");//相當於Map的put方法
    System.out.println(ps);
    System.out.println("===============");
    //3.以鍵找值
    String username = ps.getProperty("username");//相當於Map的get方法
    System.out.println(username);
    String password = ps.getProperty("password");//相當於Map的get方法
    System.out.println(password);
    System.out.println("===============");
    //4.獲取所有的鍵的集合
    Set<String> propertyNames = ps.stringPropertyNames(); //相當於Map的keySet
    System.out.println(propertyNames);
}

        4.持久化的方法***********************
            public void  store(OutputStream out/Writer out, String 註釋內容);  保存數據

public class PropertiesDemo02 {
    public static void main(String[] args) throws Exception {
        //1.創建一個Properties對象
        Properties ps = new Properties();
        //2.添加
        ps.setProperty("username", "root");//相當於Map的put方法
        ps.setProperty("password", "1234");//相當於Map的put方法
        //3.要把ps中的數據保存到mysql.txt
        ps.store(new FileWriter("mysql.properties"), null);
    }
}


            注意:如果使用Properties保存數據到文件中,該文件中的數據加載到當前Properties對象中

public class PropertiesDemo03 {
    public static void main(String[] args) throws Exception {
        //1.創建一個Properties對象
        Properties ps = new Properties();
        System.out.println(ps);
        //2.加載
        ps.load(new FileInputStream("mysql.properties"));
        System.out.println(ps);
    }
}

    總結:
        -[] 能夠使用字節輸入流讀取數據到程序
        -[] 能夠理解讀取數據ready(byte [])方法的原理
        -[] 能夠使用字節流完成文件的複製
        -[] 能夠使用FileWriter寫數據到文件
        -[] 能夠說出FileWriter中關閉和刷新方法的區別
        -[] 能夠使用FileWriter寫數據的5個方法
        -[] 能夠使用FileWriter寫數據實現換行和追加寫
        -[] 能夠使用FileReader讀數據
        -[] 能夠使用FileReader讀數據 一次一個字符數組
        -[] 能夠使用Properties的load方法加載文件中配置信息

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章