zoukankan      html  css  js  c++  java
  • 使用File I/O流简单的复制一个文件

    JAVA中的流有三种分类

    1. 处理的数据单位不同,可分为:字符流,字节流

    2.数据流方向不同,可分为:输入流,输出流

    3.功能不同,可分为:节点流,处理流

    在这边主要用到的是输入流Inputstream和输出流OutputStream

    public static void copyFile1(String src1, String src2) throws Exception {
      File f1 = new File(src1);
      File f2 = new File(src2);
      FileInputStream fis = new FileInputStream(f1);
      FileOutputStream fos = new FileOutputStream(f2);
      int len;
      byte buffer[] = new byte[50];
      while ((len = fis.read(buffer)) != -1) {
       fos.write(buffer, 0, len);
      }
      fos.close();
      fis.close();
       
      
     }

     当然,还有更快一点的方法,那就是需要用到缓冲流buffered流了,缓冲流的对象时,会创建内部缓冲数组,缺省使用32字节大小的缓冲区3.当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区4.当写入数据时,首先写入缓冲区,当缓冲区满时,其中的数据写入所连接的输出流。使用方法flush()可以强制将缓冲区的内容全部写入输出流。

    public static void copyFile1(String src1, String src2) throws Exception {
      File f1 = new File(src1);
      File f2 = new File(src2);
      FileInputStream fis = new FileInputStream(f1);
      FileOutputStream fos = new FileOutputStream(f2);
      int len;
      byte buffer[] = new byte[50];
      while ((len = fis.read(buffer)) != -1) {
       fos.write(buffer, 0, len);
      }
      fos.close();
      fis.close();
       
      
     }
    最后我们可以使用计算时间的工具类来比较一下复制的时间:
    public static void main(String[] args) {
      String x ="C:/Users/Administrator/Desktop/a.mp4";//这是文件的地址,对该文件右键属性,再点安全会出来这个地址,(记得要反译一下)

      String y ="C:/Users/Administrator/Desktop/b.mp4";//新文件的名字不能和原来的一样
      long start =System.currentTimeMillis();
      try {
       CopyFile.copyFile2(x, y);
      } catch (Exception e) {
       e.printStackTrace();
      }
      long end =System.currentTimeMillis();
      System.out.println("时间为:"+(end-start));
     }
  • 相关阅读:
    自从学会了搭建开源网站,妈妈再也不担心我找不到web自动化学习环境啦!
    领导要我6点下班前创建1000个有效的手机号,现在5点半了!教你用random模块10分钟搞定!
    python:字符串 扩展分片:第三个限制值
    python字符串:索引和分片
    测试基础:测试用例设计策略
    测试基础:软件测试思维方式
    面试整理:python列表面试习题
    面试整理:linux
    测试的一些思考
    python ConfigParse模块中的方法
  • 原文地址:https://www.cnblogs.com/Jc1995/p/13022814.html
Copyright © 2011-2022 走看看