带有缓冲区的字符流BufferedReader&BufferWriter

java.io.BufferedReader

带有缓冲区的字符输入流。

使用这个流的时候不需要自定义char数组,或者说不需要自定义byte数组,自带缓冲

public static void main(String[] args) throws IOException {
        //当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
        //外部负责包装的这个流,叫做包装流,也叫处理流。
        //在当前这个程序中,FileReader就是一个节点流。BufferedReader就是包装流/处理流。
        FileReader reader = new FileReader("temp.txt");
        BufferedReader br = new BufferedReader(reader);

        //读一行
       /* String firstLine = br.readLine();
        System.out.println(firstLine);//public class FileInputStreamTest04 {

        String secondLine = br.readLine();
        System.out.println(secondLine);//    public static void main(String[] args) {

        String thirdLine = br.readLine();
        System.out.println(thirdLine);//        FileInputStream fis = null;*/

        //br.readLine()方法读取一个文本行,但是不带换行符。
        String s = null;
        while ((s = br.readLine()) != null ){
            System.out.println(s);
        }
        //关闭流
        //对于包装流来说,只需要关闭最外层的流,里面的流在调用外部包装流的时候会自动掉用内部节点流的close()方法。
        br.close();
    }
对字节流的转换(java.io.InputStreamReader)
public static void main(String[] args) throws Exception{

        /*//字节流
        FileInputStream in = new FileInputStream("temp.txt");

        //通过转换流转换(InputStreamReader是将字节流转换成字符流)
        //in是节点流 isr就是包装流/处理流
        InputStreamReader isr = new InputStreamReader(in);

        //这个构造方法只能传一个字符流。不能传字节流。
        // isr是节点流,br就是包装流/处理流
        BufferedReader br = new BufferedReader(isr);*/
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("temp" +
                ".txt")));

        String line = null;
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }

        //关闭最外层
        br.close();
    }

java.io.BufferedWriter

public static void main(String[] args) throws Exception{
        /*BufferedWriter out = new BufferedWriter(new FileWriter("output.txt",
                true));*/
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                "output.txt",true)));

        out.write("hello world");
        out.write("\n");
        out.write("hello Kitty");


        //刷新
        out.flush();
        //关闭最外层
        out.close();

    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值