FileWriter和FileReader普通文本快捷读写的选择

本文通过具体示例介绍了如何使用FileReader进行文本文件的读取操作,以及使用FileWriter进行文本文件的写入操作。文章展示了两种读取方式:while循环读取和for循环遍历字符数组的方式,并演示了如何利用FileWriter进行文件的刷新。

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

FileWriter文件字符输出流,写

  • 只能输出普通文本
  • FileReader 文件字符输入流,只能读取普通文本
  • 读取文本内容时比较方便快捷
public class FileReaderTest {
    public static void main(String[] args) {
        FileReader reader =null;
        //创建文件字符输入流
        try {
            reader =new FileReader("fr");
            //读
            char[] chars =new char[4];
            /**
             * 采用while读
             */
            int readCount =0;
            while ((readCount=reader.read(chars))!=-1){
                System.out.println(new String(chars,0,readCount));
            }
            /**
             * 采用for读
             */
            reader.read(chars);
            for (char c:chars){
                System.out.println(c);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class FileWriterTest {
    public static void main(String[] args) {
        FileWriter out =null;
        try {
            out =new FileWriter("fw");

            //刷新
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值