在进行读取文件中数据的操作时,读取数据量大的文件时,读取的速度会很慢,Java中提供了一套缓冲流,可以提高IO流的读写速度。
缓冲流 根据流的分类分为字节缓冲流与字符缓冲流
字节缓冲流
字节缓冲流根据流的方向有字节缓冲输出流BufferedOutputStream(写入数据到流中)和字节缓冲输入流BufferedInputStream(读取流中的数据)
BufferedOutputStream 通过字节缓冲流,进行文件的读写操作 写数据到文件的操作
构造方法
public BufferedOutputStream(OutputStream out)创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
public class BufferedOutputStreamDemo01 { public static void main(String[] args) throws IOException { //写数据到文件的方法 write(); } /* * 写数据到文件的方法 * 1,创建流 * 2,写数据 * 3,关闭流 */ private static void write() throws IOException { //创建基本的字节输出流 FileOutputStream fileOut = new FileOutputStream("abc.txt"); //使用高效的流,把基本的流进行封装,实现速度的提升 BufferedOutputStream out = new BufferedOutputStream(fileOut); //2,写数据 out.write("hello".getBytes()); //3,关闭流 out.close(); } }
BufferedInputStream 完成读取文件中数据的操作
构造方法
public BufferedInputStream(InputStream in)
public class BufferedInputStreamDemo01 { public static void main(String[] args) throws IOException { //写数据到文件的方法 read(); }
/* * 从文件中读取数据 * 1,创建缓冲流对象 * 2,读数据,打印 * 3,关闭 */ private static void read() throws IOException { //1,创建缓冲流对象 FileInputStream fileIn = new FileInputStream("abc.txt"); //把基本的流包装成高效的流 BufferedInputStream in = new BufferedInputStream(fileIn); //2,读数据 int ch = -1; while ( (ch = in.read()) != -1 ) { //打印 System.out.print((char)ch); } //3,关闭 in.close(); }}
字符缓冲流
扫描二维码关注公众号,回复:
1698946 查看本文章
字符缓冲输入流BufferedReader与字符缓冲输出流BufferedWriter完成文本数据的高效的写入与读取操作
BufferedWriter 将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
方法:
void newLine() 根据当前的系统,写入一个换行符
public class BufferedWriterDemo { public static void main(String[] args) throws IOException { //创建流 //基本字符输出流 FileWriter fileOut = new FileWriter("file.txt"); //把基本的流进行包装 BufferedWriter out = new BufferedWriter(fileOut); //2,写数据 for (int i=0; i<5; i++) { out.write("hello"); out.newLine(); } //3,关闭流 out.close(); } }
BufferedReader 从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
方法:
public String readLine() 读取一个文本行,包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回null
public class BufferedReaderDemo { public static void main(String[] args) throws IOException { //1,创建流 BufferedReader in = new BufferedReader(new FileReader("file.txt")); //2,读数据 //一次一个字符 //一次一个字符数组 //一次读取文本中一行的字符串内容 String line = null; while( (line = in.readLine()) != null ){ System.out.println(line); } //3,关闭流 in.close(); } }
使用字符缓冲流完成文本文件的复制
public class CopyTextFile { public static void main(String[] args) throws IOException { //1,指定数据源, 是数据源中读数据,采用输入流 BufferedReader in = new BufferedReader(new FileReader("file.txt")); //2,指定目的地,是把数据写入目的地,采用输出流 BufferedWriter out = new BufferedWriter(new FileWriter("copyFile.txt")); //3,读数据 String line = null; while ( (line = in.readLine()) != null ) { //4,写数据 out.write(line); //写入换行符号 out.newLine(); } //5,关闭流 out.close(); in.close(); } }