随笔 - 1162  文章 - 0  评论 - 16  阅读 - 59万 

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

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

  实现:

复制代码
 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      }
复制代码

 

  图解:

    

           

           

        

 

posted on   格物致知_Tony  阅读(339)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示

目录导航