欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IO流——缓冲流的使用

程序员文章站 2024-03-07 08:32:32
...

缓冲流:BufferedInputStream、BufferedOuputStream、BufferedReader、BufferedWriter

目的:通过使用缓存,加快读取和写入数据的速度。

缓冲流是一种包装流。

IO流——缓冲流的使用示例代码:

public class TestBufferedStream {

    private static File source;
    private static File target;

    static {
        //io和bufferedstream这两个文件夹一定要存在
        source = new File("io"+File.separator+"bufferedstream"+File.separator+"source.txt");
        target = new File("io"+File.separator+"bufferedstream"+File.separator+"target.txt");

        if(!source.exists()){
            try {
                source.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(!target.exists()){
            try {
                target.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
//        testBufferedWriter();
        testBufferedOutputStream();
//        testBufferedReader();
        testBufferedInputStream();
    }

    public static void testBufferedInputStream() throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
        byte[] data = new byte[10];
        int len;
        while((len = in.read(data))!= -1){
            System.out.print(new String(data,0,len));
        }

        in.close();


    }

    public static void testBufferedOutputStream() throws IOException {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(source,false));
        out.write(65);
        byte[] data = "我是kkk".getBytes();
        String s = new String(data,0,data.length,"ASCII");//这里会乱码,因为ASCII码每个字符(数字、英文)一个字节,识别不了中文
//        out.write("bcdefghijklmnopqrst我aa叫changshuchao".getBytes());
        out.write(s.getBytes("ASCII"));
        out.flush();
        out.close();

    }

    public static void testBufferedReader() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(target));
        char[] data = new char[10];
        int len;
        while((len = reader.read(data) )!=-1){
            System.out.println(new String(data,0,len));
        }

        reader.close();
    }

    public static void testBufferedWriter() throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(source,false));
        writer.write("我");
//        writer.write(new String("叫changshuchao".getBytes("UTF-8")),0,10);
        writer.write("叫changshuchao我".toCharArray(),0,12);

        writer.close();
    }

}