首页 > 技术文章 > Java 之 IO操作-文件复制

niujifei 2020-01-26 19:03 原文

一、使用字符流复制纯文本文件

  字符流可以读取纯文本文件,而且比字节流读取的速度要快。

  实现:

 1    public void copy(String srcFileName, String destFileName) throws IOException{
 2      if(!src.isFile()){
 3             throw new RuntimeException(src.getPath() + "不存在");
 4         }
 5 
 6          //1、选择IO流,并创建IO流
 7          FileReader fr = new FileReader(srcFileName);
 8          FileWriter fw = new FileWriter(destFileName);
 9          
10          //2、一边读一边写
11          char[] arr = new char[1024];
12          int len;
13          //数据从  srcFileName文件 --> fr --> arr数组 --> fw --> destFileName
14          while((len = fr.read(arr)) != -1){
15              fw.write(arr, 0, len);
16          }
17          
18          //3、关闭
19          fw.close();
20          fr.close();
21          
22      }

 

二、使用字节流复制任意类型的文件

  字节流可以复制任意类的文件

  实现:

 1    public void copy(String srcFilename , String destFilename) throws IOException{
 2      if(!src.isFile()){
 3             throw new RuntimeException(src.getPath() + "不存在");
 4         }
 5 
 6           FileInputStream fis = new FileInputStream(srcFilename);
 7           FileOutputStream fos = new FileOutputStream(destFilename);
 8          
 9           byte[] arr = new byte[1024];
10           int len;
11           //数据: srcFilename --> fis --> arr --> fos --> destFilename
12           while((len = fis.read(arr)) !=-1){
13               fos.write(arr, 0, len);
14          }
15          
16          fis.close();
17          fos.close();
18      }

 

三、使用缓冲流复制文件

  缓冲流作为一个处理流,相对于上面两个方法来说,速度上更快了。使用缓冲流,可以提高效率,缓冲流的默认缓冲区大小是 8192 字节/字符。

  实现:

 1  public void copy(String srcFilename , String destFilename) throws IOException{
 2      if(!src.isFile()){
 3             throw new RuntimeException(src.getPath() + "不存在");
 4         }
 5 
 6          FileInputStream fis = new FileInputStream(srcFilename);
 7          BufferedInputStream bis = new BufferedInputStream(fis);
 8           
 9           FileOutputStream fos = new FileOutputStream(destFilename);
10           BufferedOutputStream bos = new BufferedOutputStream(fos);
11           
12           byte[] arr = new byte[1024];
13           int len;
14           //数据: srcFilename --> fis --> arr --> fos --> destFilename
15           while((len = bis.read(arr)) !=-1){
16              bos.write(arr, 0, len);
17           }
18          
19           bis.close(); //先关处理流
20           fis.close(); //再关节点流
21          
22           bos.close();
23           fos.close();
24      }

 

  图解:

    

           

           

        

 

推荐阅读