• 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);
                        }
                        
                    }
                }
            }
            
        }
    }
  • 相关阅读:
    Annotation
    injector
    Java容器(container)
    build tool(构建工具)maven和gradle安装方法
    version control(版本控制)
    函数式编程
    URI与URL
    超文本传输协议HTTP
    annotation的理解
    Injection
  • 原文地址:https://www.cnblogs.com/zjdbk/p/9060155.html
Copyright © 2020-2023  润新知