package cn.edu.lcudcc.byte_buffer_time; import java.io.*; public class ByteBufferTimeDemo { private static final String SRC_FILE = "/Users/baoshan/Downloads/线上教学截图/meeting_01.mp4"; private static final String DEST_FILE = "/Users/baoshan/Downloads/"; public static void main(String[] args) { // copy01(); // 低级 字节流复制 copy02(); // 低级 字节数组流复制 // copy03(); // 缓冲 字节流复制 copy04(); // 缓冲 字节数组流复制 效率高,优先使用 } private static void copy01() { long startTime = System.currentTimeMillis(); try{ InputStream is = new FileInputStream(SRC_FILE); OutputStream os = new FileOutputStream(DEST_FILE+"video1.mp4"); int b; while ((b = is.read()) != -1) { os.write(b); } os.flush(); os.close(); is.close(); } catch (Exception e){ e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("使用低级的字节流按照一个一个字节的形式复制文件耗时:" + (endTime - startTime) / 1000.0 + "s"); } private static void copy02() { long startTime = System.currentTimeMillis(); try { InputStream is = new FileInputStream(SRC_FILE); OutputStream os = new FileOutputStream(DEST_FILE + "video2.mp4"); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1){ os.write(buffer, 0, len); } os.flush(); os.close(); is.close(); } catch (Exception e){ e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("使用低级的字节流数组按照一个一个字节的形式复制文件耗时:" + (endTime - startTime) / 1000.0 + "s"); } private static void copy03() { long startTime = System.currentTimeMillis(); try{ InputStream is = new FileInputStream(SRC_FILE); BufferedInputStream bis = new BufferedInputStream(is); OutputStream os = new FileOutputStream(DEST_FILE+"video3.mp4"); BufferedOutputStream bos = new BufferedOutputStream(os); int b; while ((b = bis.read()) != -1) { bos.write(b); } bos.flush(); bos.close(); bis.close(); os.close(); is.close(); } catch (Exception e){ e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("使用缓冲的字节流按照一个一个字节的形式复制文件耗时:" + (endTime - startTime) / 1000.0 + "s"); } private static void copy04() { long startTime = System.currentTimeMillis(); try { InputStream is = new FileInputStream(SRC_FILE); BufferedInputStream bis = new BufferedInputStream(is); OutputStream os = new FileOutputStream(DEST_FILE+"video4.mp4"); BufferedOutputStream bos = new BufferedOutputStream(os); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1){ bos.write(buffer, 0, len); } bos.flush(); bos.close(); bis.close(); os.close(); is.close(); } catch (Exception e){ e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("使用缓冲的字节流数组按照一个一个字节的形式复制文件耗时:" + (endTime - startTime) / 1000.0 + "s"); } }
结论:高级缓冲字节数组流复制,效率最高,优先使用。
标签:Java,字节,System,FILE,close,new,拷贝,os From: https://www.cnblogs.com/zhzhang/p/17003447.html