复制文件(最正确的写法) java

329 阅读1分钟

缓存 new byte[101024];大小可根据实际情况定,如果文件很大,比如大于1G,可以设定为101024*1024

//都文件内容到内存
        File file = new File("kk.avi");

//        读文件
        FileInputStream fileInputStream = new FileInputStream(file);
//        写文件
        FileOutputStream fileOutputStream = new FileOutputStream("kk3.avi");
        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
        System.out.println("start:  "+format.format(date));
//        每次读10k
        byte[] bytes = new byte[10*1024];

        int readLength = 0;
        while ((readLength=fileInputStream.read(bytes))!=-1){
//                System.out.println("readLength= " +readLength);

           fileOutputStream.write(bytes,0,readLength);
        }

        fileInputStream.close();
        fileOutputStream.close();
        Date date1=new Date();
        DateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
        System.out.println("end:  "+format1.format(date1));