侧边栏壁纸
博主头像
小顺

一帆风顺 ⛵️⛵️⛵️

  • 累计撰写 70 篇文章
  • 累计创建 0 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

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

小顺
2021-08-17 / 0 评论 / 0 点赞 / 27 阅读 / 165 字

关闭外层处理流(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();
            }
        }

    }
}
0

评论区