铂西学习日记---字符流的基本使用

字节流的基本使用与简单介绍icon-default.png?t=M0H8https://blog.csdn.net/qq_31671169/article/details/122745963?spm=1001.2014.3001.5501

字符流:原理实际上用的还是字节流最终指向父类的方法,参数为new FileIn(Out)putStream()

 

import java.io.*;

public class demo_io2 {
    public static void main(String[] args) {
        /**字符流
         * 字符输出流:Writer,对文件的操作使用子类:FileWriter
         * 字符输入流:Reader,对文件的操作使用子类:FileReader
         * 每次操作的单位是一个字符,其底层原理还是调用 FileOutStream 和 FileInputStream,即内部实现还是字节流
         * 文件字节流操作没有缓存,执行写入操作时会直接写入文件
         * 文件字符操作流会自带缓存,默认大小为1024 --> private static final int WRITE_BUFFER_SIZE = 1024; 在缓存满后,手动刷新(flash()方法)或关闭流才会真正的把数据写入文件
         *
         *
         * 如何选择字节流或字符流:操作非文本文件的时候使用字节流,操作文本文件的时候建议使用字符流
         */
//        out();
        in();
    }
    public static void out(){
        File file = new File("1.txt");
        try {
            Writer out = new FileWriter(file,true);
            out.write("你好!");
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void in(){
        File file = new File("1.txt");
        try {
            Reader in = new FileReader(file);
            //每次读取一个字符,所以需要一个字符数组
            char[] chars = new char[1];
            int len = -1;
            StringBuilder sb = new StringBuilder();
            while ((len=in.read(chars))!=-1){
                sb.append(chars,0,len);
            }
            System.out.println(sb);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小狗铂西

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值