MENU

BufferedIo

June 25, 2018 • Read: 2859 • Java阅读设置

缓冲流

缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法

BufferedReader(Reader in)
BufferedReader(Reader in,int sz)//sz为自定义缓冲区的大小
BufferedWriter(Writer out)
BufferedWriter(Writer out,int sz)
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in,int size)
BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out,int size)
  • 缓冲输入流支持其父类的mark和reset方法
  • BufferedReader提供了ReadLine方法用于读取一行字符串(以r或n分隔)
  • BufferedWriter提供了newLine用于写入一个分隔符
  • 对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush方法将会使内存中的数据立刻写出

BufferedInputStream

import java.io.*;

public class TestFileInputStream {
    public static void main(String[] args) {
        try {
            FileInputStream fis = 
                    new FileInputStream("D:/test.txt");
            BufferedInputStream bis = 
                    new BufferedInputStream(fis);
            int c = 0;
            System.out.println(bis.read());
            System.out.println(bis.read());
            bis.mark(100);//标记第100个字符,从第100个字符往外读
            for(int i = 0;i <= 10 && (c = bis.read()) != -1;i++) 
                System.out.println((char)c + " ");
            System.out.println();
            bis.reset();//回到标记
            for(int i = 0;i <= 10 && (c = bis.read()) != -1;i++)
                System.out.println((char)c + " ");
            bis.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedReader(Writer)

import java.io.*;

public class TestBuffered{

    public static void main(String[] args) {
        try {
            BufferedWriter bw = 
                    new BufferedWriter(new FileWriter("D:/test4.txt"));
            BufferedReader br = 
                    new BufferedReader(new FileReader("D:/test4.txt"));
            String s = null;
            for(int i = 1;i <= 100;i++) {//写入100行随机数
                s = String.valueOf(Math.random());
                bw.write(s);
                bw.newLine();
            }
            bw.flush();
            while((s = br.readLine()) != null) {
                System.out.println(s);
            }
            bw.close();
            br.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}
Last Modified: October 19, 2018
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment