JAVA单排日记-2020/1/26-练习_文件的复制

在这里插入图片描述
将copy.jpg复制到新建文件夹中

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

public class DemoCopy {
    public static void main(String[] args) throws IOException {
        FileInputStream file = new FileInputStream("G:\\Java\\测试文件夹\\copy.jpg");
        int len =0;
        byte[] bytes = new byte[221184];
        while ((len=file.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }
        file.close();

        FileOutputStream file01 = new FileOutputStream("G:\\Java\\测试文件夹\\新建文件夹\\copy02.jpg");
        file01.write(bytes);
        file01.close();
    }
}

在这里插入图片描述

优化:一边读一边写:

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

public class DemoCopy {
    public static void main(String[] args) throws IOException {
        long s=System.currentTimeMillis();//用于测试程序运行时间

        FileInputStream file = new FileInputStream("G:\\Java\\测试文件夹\\copy.jpg");
        FileOutputStream file01 = new FileOutputStream("G:\\Java\\测试文件夹\\新建文件夹\\copy02.jpg");

        int len =0;
        byte[] bytes = new byte[221184];
        while ((len=file.read(bytes))!=-1){
            file01.write(bytes,0,len);
        }
        file.close();
        file01.close();

        long e = System.currentTimeMillis();//测试程序耗时
        System.out.println("耗时:"+(e-s)+"s");//测试程序耗时
    }
}

在这里插入图片描述

发布了103 篇原创文章 · 获赞 1 · 访问量 2651

猜你喜欢

转载自blog.csdn.net/wangzilong1995/article/details/104088828