IO缓存流

2019-04-19  本文已影响0人  test_dw

为啥要缓存流?

什么是缓存流?

字节流与缓存流

使用BufferedReader缓存流读取数据

package twodoge;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public static void main(String args[]){
    File f = new File('D:twodoge.txt');
    //创建文字字符流
    //缓存流必须建立在一个基础流上
    try(
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
    )
    {
        while(True){
            String line = br.readLine();
            if(line == null)
                break;
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

使用PringWriter缓存流写出数据

package twodoge;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

public class myPrintWriter {
    public static viod main(String args[]) {

        File f = new File("D://twodoge.txt");
        try (
            FileWriter fw = new FileWriter(f);
            PrintWriter pw = new PrintWriter(fw);
        )
        {
            pw.printWriter("test1");
            pw.printWriter("test2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

flush

package twodoge;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

public class myPrintWriter {
    public static viod main(String args[]) {

        File f = new File("D://twodoge.txt");
        try (
            FileWriter fw = new FileWriter(f);
            PrintWriter pw = new PrintWriter(fw);
        )
        {
            pw.println("test1");
            fw.flush();
            pw.println("test2");
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读