I/O(FileInputStream 和FileOutputStream实现图片复制)

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


package com.apesblog.day_26;

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

public class Test4 {

    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = 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);
            while ((len = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}