package java7; import org.junit.Test; import java.io.*; /** * 处理流之一:缓冲流的使用 * 1.缓冲流: * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter * 2.作用:提高流的读取和写入效率 * 原因:内部提供缓冲区 * * @author 冀帅 * @date 2020/8/19-17:02 */ public class BufferedTest { /* *实现非文本文件的复制 * * */ @Test public void test() { // 1.造文件 BufferedInputStream bis = null; BufferedOutputStream bos = null; try { File file = new File("IMG_20200817_113832.jpg"); File file1 = new File("123456789.jpg"); // 2.造流 // 2.1 造节点流 FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(file1); // 2.2 造缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); // 3.复制的细节:读取和写入 byte[] Bytes = new byte[1024]; int len; while ((len = bis.read(Bytes)) != -1) { bos.write(Bytes, 0, len); // bos.flush();//刷新缓冲区 } } catch (IOException e) { e.printStackTrace(); } finally { // 4.关闭流:先关外层流,再关闭内层流 try { if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } } // //说明:关闭外层时,会自动关内层 // fis.close(); // fos.close(); } //实现文件复制的方法 public void copyFileWithBuffered(String srcPath, String destPath) { // 1.造文件 BufferedInputStream bis = null; BufferedOutputStream bos = null; try { File file = new File(srcPath); File file1 = new File(destPath); // 2.造流 // 2.1 造节点流 FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(file1); // 2.2 造缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); // 3.复制的细节:读取和写入 byte[] Bytes = new byte[1024]; int len; while ((len = bis.read(Bytes)) != -1) { bos.write(Bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { // 4.关闭流:先关外层流,再关闭内层流 try { if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } } // //说明:关闭外层时,会自动关内层 // fis.close(); // fos.close(); } @Test public void testcopy(){ long start = System.currentTimeMillis(); String srcPath = "D:\\狂神说java\\_狂神说Java_JavaWeb入门到实战3.mp4"; String destPath = "D:\\狂神说java\\_狂神说Java_JavaWeb入门到实战666.mp4"; copyFileWithBuffered(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("复制操作花费的时间为:"+(end-start));//1165 } }