65. 练习(拷贝图片--边读边写)

public class Demo3 {
    public static void main(String[] args) {
        File inputfile = new File("D:\\新建文件夹 (2)\\1.jpg");
        File outputfile = new File("D:\\新建文件夹\\1.jpg");
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        
        try {
            fileInputStream = new FileInputStream(inputfile);
            fileOutputStream = new FileOutputStream(outputfile);
            byte[] buf = new byte[1024];
            int length = 0;
            while((length = fileInputStream.read(buf))!=-1) {
                //这里我们用了三个参数的write方法,因为我们不知道最后一次读取的数据是不是有1024个字节,
                //为了防止图片拷贝后文件会变得大,我们在这里用了一个截取长度,
                //其实write(byte[] b)方法底层还是靠这个方法实现的,只不过截取长度是字节数组的长度而已
                fileOutputStream.write(buf, 0,length );
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //边读边写规则:先开后关
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }finally {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    
                }
            }
        }
        
    }
}

猜你喜欢

转载自www.cnblogs.com/zjdbk/p/9060155.html