java基础-io-复制文件

以字节为单位复制文件(文件大的复制很慢)

public class CopyFileDemo {
    public static void main(String[] args)  {
        String src = "/Users/xxx/Desktop/study01/src/main/java/iodemo/CopyFileDemo.java";
        String deString = "/Users/xxx/Downloads/test/test01.java";
        copyFile(src,deString);
    }
    public static void copyFile(String srcFile,String deFile)  {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try{
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(deFile);
            int cc = fis.read();
            //如果cc不是-1 把cc保存到目标文件中
            while (cc != -1){
                fos.write(cc); //把读到的字节cc保存到输出流中
                cc=fis.read();
            }

        }catch (IOException e){
            e.printStackTrace();

        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}

以字节数组为单位复制文件(解决文件大的复制很慢的问题)- 不需要关闭流

public class CopyFileDemo {
    public static void main(String[] args) {
        String src = "/Users/xxx/Desktop/study01/src/main/java/iodemo/CopyFileDemo.java";
        String deString = "/Users/xxx/Downloads/test/test03.java";
        copyFile1(src, deString);
    }

    public static void copyFile1(String srcFile, String deFile) {
        try (FileInputStream fis1 = new FileInputStream(srcFile);
             FileOutputStream fos1 = new FileOutputStream(deFile);) {

            byte[] bytes = new byte[1024];
            int len = fis1.read(bytes);
            while (len != -1) {
                fos1.write(bytes, 0, len); //把读到的字节数组保存到输出流中
                len = fis1.read(bytes);
            }

        } catch (IOException e) {
            e.printStackTrace();

        }

    }
}
上一篇:Lottie动画资源放到服务器预下载,一文说清


下一篇:制作正方体html+css3(动画)