I/O(BufferedInputStream和BufferedOutputStream实现非文本文件的复制)

发布于 2021-08-13  54 次阅读


关闭外层处理流(bufferInputStream、bufferedOutputStream),内层节点流(fileInputStream、fileOutputStream)也自动关闭。

package com.apesblog.day_26;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test5 {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedInputStream bufferInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            File file = new File("src/com/apesblog/day_26/1.png");
            File file2 = new File(file.getParent(), "copy.png");
            byte[] buffer = new byte[1024];
            int len;
            fileInputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream(file2);
            bufferInputStream = new BufferedInputStream(fileInputStream);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            while ((len = bufferInputStream.read(buffer)) != -1) {
                bufferedOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferInputStream != null)
                    bufferInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bufferedOutputStream != null)
                    bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}