IO流(9)--字符流的三种拷贝

本文详细介绍了Java中字符流的基本使用方法,包括FileReader和FileWriter的读写操作,字符流的拷贝过程,以及如何利用缓冲区提高拷贝效率。通过具体的代码示例展示了如何实现文件内容的读取、写入及复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符流FileReader

public static void main(String[] args) throws IOException {
        FileReader fr=new FileReader("xxx.txt");
        int b;
        while((b=fr.read())!=-1){
            System.out.print((char)b);  //因为是中文,所以要强制转换
        }

        fr.close();
    }

FileWriter

public static void main(String[] args) throws IOException {
        FileWriter fw=new FileWriter("yyy.txt");
        fw.write("大家好,hahaha");

        fw.write(97);   //会写一个  a  在文件yyy.txt中
        fw.close();
    }

字符流的拷贝

public static void main(String[] args) throws IOException {
        FileReader fr=new FileReader("xxx.txt");
        FileWriter fw=new FileWriter("yyy.txt");

        int c;
        while((c=fr.read())!=-1){
            fw.write(c);
        }

        fr.close();
        fw.close(); 
        //writer类中有一个2K的缓冲区,如果不关流,就会将内容写到缓冲区里
    }

带有数组的拷贝

public static void main(String[] args) throws IOException {
        FileReader fr=new FileReader("xxx.txt");
        FileWriter fw=new FileWriter("yyy.txt");

        char[] arr=new char[1024];
        int len;
        while((len=fr.read(arr))!=-1){  //将文件上的数据读取到字符数组中
            fw.write(len);              //将字符数组中的数据写到文件上

        }

        fr.close();
        fw.close();
    }

带有缓冲区的字符流拷贝

public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new FileReader("xxx.txt"));
        BufferedWriter bw=new BufferedWriter(new FileWriter("zzz.txt"));

        int b;
        while((b=br.read())!=-1){
            bw.write(b);
        }

        br.close();
        bw.close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值