使用java缓冲流实现文件的复制
文件的复制我们一般使用java的缓冲流,因为缓存流较节点流更快。
步骤:
1、创建源文件、目标文件
2、创建输入节点流、输出节点流
3、创建输入缓冲流、输出缓冲流
4、将文件读入到内存然后写出到目的地址
5、关闭流(关闭流的顺序是先关闭外层再关闭内层流,但是关闭外层流的同时内层流会自动关闭,所以只需要关闭外层流即可)
1、创建源文件、目标文件
File srcFile = new File(srcPath); File destFile = new File(destPath);
2、创建输入节点流、输出节点流
FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile);
3、创建输入缓冲流、输出缓冲流
bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos);
4、将文件读入到内存然后写出到目的地址
byte[] buffer = new byte[10]; int len; while ((len=bis.read(buffer))!=-1){ bos.write(buffer,0,len); }
5、关闭流(关闭流的顺序是先关闭外层再关闭内层流,但是关闭外层流的同时内层流会自动关闭,所以只需要关闭外层流即可)
bos.close(); bis.close();
最后加上异常处理,并将其抽取到工具类中,代码如下
/** * @author 齐天大圣 * @Version 1.0 */ public class FileUtiles { public static void f(String srcPath,String destPath){//源文件路径,目标文件路径 BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1、创建源文件、目标文件 File srcFile = new File(srcPath); File destFile = new File(destPath); //2、创建输入节点流、输出节点流 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); //3、创建输入缓冲流、输出缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //4、将文件读入到内存然后写出到目的地址 byte[] buffer = new byte[10]; int len; while ((len=bis.read(buffer))!=-1){ bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //5、关闭流(关闭流的顺序是先关闭外层再关闭内层流,但是关闭外层流的同时内层流会自动关闭,所以只需要关闭外层流即可) // bos.close(); // bis.close(); if (bos!=null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (bis!=null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } // fos.close(); // fis.close(); } } }
测试
复制后