Java字節流之輸入、輸出流

字節流

字節流(總體參照是自己的程序)
輸出:程序-->文件
輸入:文件-->程序

字節輸出流

字節輸出流(OutPut) -- 寫文件
OutPutStream是抽象類(不能實例化對象)並且是所有輸出流的父類
一次寫入一個字節(一字節是8個二進制位)
    /*
     * 構造方法:
     * 參數 1.文件(被寫入的文件)
     *      2.文件路徑(被寫入的路徑)
     * 
     * 寫入文件的流程:
     * 1.綁定要寫入的文件 或 文件路徑
     * 2.使用write方法寫入
     * 3.關閉資源
     */
    public static void main(String[] args) throws IOException {
        // 該路徑下沒有該文件會幫你創建出這個文件
        // 如果已經有了該文件文件會被覆蓋
        // 綁定數據的目的地(綁定要寫入的文件)
        File file = new File("/Users/lanou/Desktop/level/yin.txt");
        FileOutputStream oStream = new FileOutputStream(file);

        // 寫入數據 按ASCII表的值輸入的
        oStream.write(48);

        // 用字節數組寫入
        byte[] b = {65,66,67,68};
        oStream.write(b);
        // 按字節數組的索引和長度寫入
        oStream.write(b, 0, 3);

        // 簡單寫法
        oStream.write("hello".getBytes());
        oStream.write("world".getBytes());

        // 關閉資源
        oStream.close();
    }
文件的續寫和換行:
    public static void main(String[] args) throws IOException {
        File file = new File("/Users/lanou/Desktop/level/gs.txt");
        FileOutputStream oStream = new FileOutputStream(file, true);
        oStream.write("hello\n".getBytes());
        oStream.close();
    }
    /*
     * 異常處理
     * IO發生異常 都需要停止程序 修改代碼
     */

    public static void main(String[] args) throws IOException {
        File file = new File("/Users/lanou/Desktop/level/gs.txt");
        // 增加作用域
        FileOutputStream oStream = null;
        try {
            // 創建了一個流
            oStream = new FileOutputStream(file);
            oStream.write("hello".getBytes());
        } catch (FileNotFoundException e) {
            // 拋出一個運行時異常(直接停止掉程序)
            throw new RuntimeException("文件找不到");
        } catch (IOException e) {
            // 文件編寫失敗 直接停止掉程序
            throw new RuntimeException("文件編寫失敗");
        } finally {
            // 關閉資源
            try {
                // 非空判斷
                // 如果是空的 說明流創建失敗 失敗就不需要關閉
                if (oStream != null) {
                    // 只要是你手動創建的流你就需要手動關閉
                    oStream.close();
                }
            } catch (IOException e) {
                // 關閉資源失敗 直接停止掉程序
                throw new RuntimeException("關閉失敗");
            }
        }
    }

字節輸入流

字節輸入流(Input) -- 讀文件
InputStream是抽象類不能實例化對象並且是所有輸入流的父類
注意:讀取是一個字節一個字節的讀
讀取文件流程
    1.綁定數據源文件
    2.使用read方法讀
    3.關閉資源

    public static void main(String[] args) throws IOException{
        // 綁定數據的目的地(綁定要寫入的文件)
        File file = new File("/Users/lanou/Desktop/level/znb.txt");
        FileInputStream iStream = new FileInputStream(file);
        // 讀取
        int i1 = iStream.read();
        System.out.println((char)i1);
        i1 = iStream.read();
        System.out.println((char)i1);
        i1 = iStream.read();
        System.out.println((char)i1);
        i1 = iStream.read();
        System.out.println((char)i1);
        i1 = iStream.read();
        System.out.println((char)i1);
        i1 = iStream.read();
        // 當讀取到文件末尾的時候 會返回-1
        // 相當於 你讀到-1 文件都讀完了
        System.out.println(i1);
        // 關閉資源
        iStream.close();
    }
循環讀取:

    public static void main(String[] args) throws IOException{
        File file = new File("/Users/lanou/Desktop/level/znb.txt");
        FileInputStream iStream = new FileInputStream(file);
        // 聲明一個變量 保存讀出來的結果
        int num = 0;
        while ((num=iStream.read()) != -1) {
            System.out.println((char)num);
        }
        iStream.close();
    }
注意:read方法每調用一次就讀取一個字節,循環的時候read方法只能出現一次
使用字節數組讀取文件:

    public static void main(String[] args) throws IOException{
        // 使用字節數組讀取文件
        File file = new File("/Users/lanou/Desktop/level/znb.txt");
        FileInputStream iStream = new FileInputStream(file);
        // 聲明瞭一個長度爲2的 空的 字節數組
        // 讀取時 會把讀出來的內容放進字節數組中 存儲
        byte[] b = new byte[2];
        int i1 = iStream.read(b);
        System.out.println(i1); // 2 有效讀取個數
        // 利用字符串的構造方法直接打印字符串
        System.out.println(new String(b)); // ab

        i1 = iStream.read(b);
        System.out.println(i1); // 2
        // 利用字符串的構造方法直接打印字符串
        System.out.println(new String(b)); // cd

        i1 = iStream.read(b);
        System.out.println(i1); // 1
        // 利用字符串的構造方法直接打印字符串
        System.out.println(new String(b)); // ed

        i1 = iStream.read(b);
        System.out.println(i1); // -1
        // 利用字符串的構造方法直接打印字符串
        System.out.println(new String(b)); // ed
        iStream.close();
    }

字節的輸入輸出流練習

使用字節的輸入輸出流進行文件的複製:

public class Demo01 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        // 異常處理 的複製文件
        // 讀
        FileInputStream iStream = null;
        // 寫
        FileOutputStream oStream = null;
        try {
            iStream = new FileInputStream("/Users/lanou/Desktop/level/9.jpg");
            oStream = new FileOutputStream("/Users/lanou/Desktop/level/10.jpg");
            // 讀一個字節 寫一個字節
            /*
            int len = 0;
            while ((len = iStream.read()) != -1) {
                // 直接把讀出來的寫進文件
                oStream.write(len);
            }
            */
            // 用字節數組的方式讀寫 利用緩衝數組讀寫 效率較高
            byte[] b = new byte[1024];
            int num = 0;
            while ((num = iStream.read(b)) != -1) {
                oStream.write(b, 0, num);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("文件找不到");
        } catch (IOException e) {
            throw new RuntimeException("文件複製失敗");
        } finally {
            // 這時讀取和寫入都完事了 先關哪個都可以
            try {
                if (iStream != null) {
                    iStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("關閉資源失敗");
            } finally {
                // 寫一起的話 如果第一個報了異常 第二個流會無法關閉
                try {
                    if (oStream != null) {
                        oStream.close();
                    }

                } catch (IOException e) {
                    throw new RuntimeException("關閉資源失敗");
                }
            }
        }
        // 獲取結束時間
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
將一個文件夾複製到另一個文件夾:
public class Demo02 {
    public static void main(String[] args) throws IOException {
        File file1 = new File("/Users/lanou/Desktop/level");
        File file2 = new File("/Users/lanou/Desktop/XTest");
        copyFile(file1, file2);
    }
    /*
     * 複製文件夾方法
     * 參數
     * file1 源文件(要被複制的)
     * file2 目標文件夾(要把原文件夾複製進去)
     */
    public static void copyFile(File file1,File file2) throws IOException {
        // 在目標文件夾下創建 新的文件夾 名字跟源文件夾一樣
        File newDir = new File(file2, file1.getName());
        newDir.mkdir();
        /*
         * 複製文件 ---> 找到文件 ---> 一邊讀一邊寫
         *         ---> 找到文件夾 ---> 繼續調用本方法
         */
        // 遍歷源文件夾
        File[] listFiles = file1.listFiles();
        for (File file3 : listFiles) {
            if (file3.isDirectory()) {
                // 需要創建文件夾 繼續遍歷讀寫
                copyFile(file3, newDir);
            } else {
                FileInputStream iStream = new FileInputStream(file3);
                // 要在新建的文件夾下寫入 newDir + file1.getName
                File tempFile = new File(newDir, file3.getName());
                FileOutputStream oStream = new FileOutputStream(tempFile);
                byte[] b = new byte[1024];
                int num = 0;
                while ((num = iStream.read(b)) != -1) {
                    oStream.write(b, 0, num);
                }
                iStream.close();
                oStream.close();
            }
        }
    }
}
將一個文件夾下的txt文件複製到另一個文件夾:
public class Demo03 {
    public static void main(String[] args) throws IOException {
        File file1 = new File("/Users/lanou/Desktop/level");
        File file2 = new File("/Users/lanou/Desktop/XTest");
        getTXTFile(file1, file2);
    }
    public static void getTXTFile(File file1,File file2) throws IOException {
        File[] listFiles = file1.listFiles(new FilterTXT());
        for (File file : listFiles) {
            if (file.isFile()) {
                FileInputStream iStream = new FileInputStream(file);
                File tempFile = new File(file2, file.getName());
                FileOutputStream oStream = new FileOutputStream(tempFile);
                byte[] b = new byte[1024];
                int num = 0;
                while ((num = iStream.read(b)) != -1) {
                    oStream.write(b, 0, num);
                }
                iStream.close();
                oStream.close();
            } else {
                getTXTFile(file, file2);
            }
        }
    }
}

// 過濾txt文件
class FilterTXT implements FileFilter {

    @Override
    public boolean accept(File pathname) {
        // 不過濾文件夾
        if (pathname.isDirectory()) {
            return true;
        }
        return pathname.getName().endsWith("txt");
    }   
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章