java中IO流-缓冲流(字符型)复制操作

复制代码
import java.io.*;

public class BufferedTest {
  public static void main(String[] args) {
        
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        
        long start = System.currentTimeMillis();
        try {
            // 1.实例化File类的对象,指明要操作的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello1.txt");
            
            // 2.1造字节流
            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);
            // 2.2造缓冲流
            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);
            
            // 3.复制的细节:读取写入
            char[] cbuf = new char[1024];
            int len;
            while ((len = br.read(cbuf)) != -1) {
                bw.write(cbuf, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {// 4.关闭资源
            // 要求:先关闭外层的流,再关闭内层的流
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 可以省略(关闭外层流的同时,内层流也会自动的进行关闭)
//            if (fw != null) {
//                try {
//                    fos.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (fr != null) {
//                try {
//                    fis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
        }
        long end = System.currentTimeMillis();
        System.out.println("复制花费的时间为:" + (end - start));
    }
}
复制代码

 

posted @   lai_xinghai  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示