Java中I/O流之缓冲流

Posted 牧羊人的世界

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中I/O流之缓冲流相关的知识,希望对你有一定的参考价值。

Java 中的缓冲流:

  1. 缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法(带缓冲区的,显著减少对 IO 的读写次数,保护硬盘).

  2. J2SDK 提供了四种缓冲流,其常用构造方法如下:

    2.1 BufferedReader(Reader in) // 带缓冲区的输入流;

          BufferedReader(Reader in, int size) // 自定义缓冲区的大小;

    2.2 BufferedWriter(Writer out) // 带缓冲区的输出流;

      BufferedWriter(Writer in, int size) // 自定义缓冲区的大小;  

    2.3 BufferedInputStream(InputStream in)

      BufferedInputStream(InputStream in, int size)

    2.4 BufferedOutputStream(OutputStream out)

        BufferedOutputStream(OutputStream out, int size)

  3. 缓冲输入流支持其父类的 mark 和 reset 方法.

  4. BufferedReader 提供了 readLine 方法用于读取一行字符(以 \r 或 \n 分隔).

  5. BufferedWriter 提供了 newLine 用于写入一个行分隔符.

  6. 对于输出的缓冲流,写出的数据会先在内存中缓存,可以使用 flush 方法使内存中的数据立刻写出.

Demo_1:

import java.io.*;
class Test {
	public static void main(String[] args) {
		try {
			FileInputStream fis = new FileInputStream("E:/eclipse projiect/data.txt");
			BufferedInputStream bis = new BufferedInputStream(fis); // 有了带缓冲区的功能
			int c = 0;
			System.out.println(bis.read()); // (char)bis.read
			System.out.println(bis.read()); // (char)bis.read
			bis.mark(100); // 将标记放到第100个字符,从第100个字符开始读;
			for(int i=0;i<=20 && (c=bis.read())!=-1;i++){ // ASCII(13\10)回车换行
				System.out.print(c+" "); // (char)c
			}
			System.out.println();
			bis.reset();
			for(int i=0;i<=20 && (c=bis.read())!=-1;i++){
				System.out.print(c+" "); // (char)c
			}
			bis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e){
			e.printStackTrace();
		}
	}
} 

 运行结果:

105
109
112 111 114 116 32 106 97 118 97 46 105 111 46 70 105 108 101 73 110 112 117
112 111 114 116 32 106 97 118 97 46 105 111 46 70 105 108 101 73 110 112 117

Demo_2:

 




以上是关于Java中I/O流之缓冲流的主要内容,如果未能解决你的问题,请参考以下文章

I/O流之字节流

java的 IO流之缓冲流(转载)

IO流之缓冲流

缓冲流之字节缓冲流

JAVA SE基础篇51装饰流之缓冲流和转换流

Java IO流之字符缓冲流