Java 字符流 详解

java基础(jdk1.8)

**

文件IO——字符流

**

Java操作char来实现流的输入输出,前文说过输入输出是相对Java而言的。

字符流标识每次进行IO时最小单位为1字符,也就是1char

字符流和字节流基本内容一致,区别就在于byte和char

字符输出流

Writer 接口为字符输出流顶类

子类

  • FileWriter(只能写入到文本文件)

方法

write(int);		//向文件写入一个字符
			
write(char []); //向文件中写入字符数组

write(char [],int,int);	//向文件从char的int开始,共int个字符

write(String);	//写入字符串

字符输入流

Reader 接口为字符输入流顶类

子类

  • FileReader(只能读文本文件)

方法

read();
			
read(char []);

读写文件

读:

try {
    Reader read = new FileReader("d:\\a.txt");
    int len;
    
    //1 char字符  = 2 byte(字节)
    char [] c = new char[10];
    
    while ((len = read.read(c)) != -1)
    {
        System.out.print(new String(c,0,len));
    }
    
} catch (IOException e) {
    e.printStackTrace();
}

写:

try {
    Writer writer = new FileWriter("d:\\a.txt",true);

    writer.write("字符流");

    //写入时需要调用flush方法进行一次刷新,如果写操作很多的话比较消耗性能,
    //因此调用flush之后才会写入之前写入缓存的内容
    writer.flush();

    writer.close();

} catch (IOException e) {
    e.printStackTrace();
}

复制文件:

public static void main(String[] args){
    FileReader fr = null;
    FileWriter fw = null;
    try {

        fr = new FileReader("d:\\a.txt");
        fw = new FileWriter("d:\\c.txt");
        int len;
        char [] chars = new char[1024];

        while ((len = fr.read(chars)) != -1)
        {
            fw.write(chars,0,len);
            fw.flush();
        }


    } catch (FileNotFoundException e) {
        
        System.err.println("文件未找到或权限不够");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fw != null)
        {
            try {
                fw.close();
            } catch (IOException e) {
                System.out.println("输出流关闭异常");
            }
        }
        if (fr != null)
        {
            try {
                fr.close();
            } catch (IOException e) {
                System.out.println("输入流关闭异常");
            }
        }
    }

}

注意:

  • 字符流是专门针对文本文件,一般来说纯英文的文本也可以使用字节流,但建议使用字符流操作文本文件

  • 一般使用流时,如果使用完毕要进行close操作,流进行close要进行判空,因此代码看起来比较臃肿。

下一节转化流针对中文乱码进行说明!!!
有兴趣的关注我的公众号,一起学习交流啊
在这里插入图片描述

上一篇 》字节流


下一篇 》转换流

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值