字符流使用

文件字符流
字符流的两个抽象父类:字符输出流:Writer 和字符输入流:Reader

OutputStreamWriter 类的成员方法

public void write(int c):写一个字符

public void write(char[] cbuf):写一个字符数组

public void write(char[] cbuf,int off,int len):写一个字符数组的一部分

public void write(String str):写一个字符串

public void write(String str,int off,int len):写一个字符串的一部分

flush():刷新缓冲区

close():关闭流对象

BufferedReader/BufferedWriter,字符缓存流(处理流),与BufferedInputStream/BufferedOutputStream类似,增加了缓存机制,大大提高了读写文本文件的效率。

BufferedReader/BufferedWriter也可以对FileReader/FileWriter进行装饰,然后继续使用read()方法。

public static void main(String[] args) throws IOException {
        File f1=new File("d:/a.txt");
        BufferedReader br=new BufferedReader(new FileReader(f1));
 
        //可以按行去读取
        String line= br.readLine();//一直读取,直到读取到了换行符为止
        System.out.println(line);
 
        String line1= br.readLine();
        System.out.println(line1);
 
        //读取到最后一行在读取获取的是null
        String line2= br.readLine();
        System.out.println(line2);
}

输入流:Reader

public class ReaderTest {
    public static void main(String[] args) throws IOException {
        File f1=new File("d:/a.txt");
//        Reader r=new FileReader(f1);
        BufferedReader inp=new BufferedReader(new FileReader(f1));

//        int n= inp.read();//所有的中文字符按照一个字符处理,每次读取一个字符,把该字符转换成对应的编码值
//        System.out.println((char)n);

//        int n1= inp.read();
//        System.out.println((char)n1);

//        //使用缓冲区读取多个字符
 char[] c=new char[10];
       int n = inp.read(c);//次最多读取buffer数组长个字符,把读取到的字符存入buffer数组中,返回的是实际读取到的字符数system.out.println(n);
        System.out.println(n);
        System.out.println(Arrays.toString(c));

        char[] c1=new char[10];
        int n1=inp.read(c1);
        System.out.println(n1);
        System.out.println(Arrays.toString(c1));
    }
}

输出流:Writer

 public static void main(String[] args) throws IOException {
        File f2=new File("D:/b.txt");
    if(!f2.exists()){
        f2.createNewFile();
    }
    //定义一个字符输出流,向f2文件写入内容
        Writer out=new FileWriter(f2,true);

    out.write(97);

    out.write((int)'中');

    char[] c={'河','南','南','阳'};
    out.write(c);

    out.write("奥里给");
    out.write("abcdef",0,3);

    out.flush();//字符输出流有缓冲区的概念  需要刷新缓冲区才更新硬盘
    out.close();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值