其实这一篇文章主要是对IO流做了一个阶段性的总结,就是使用缓冲区的高效性来读取和写入字节流或者是字符流。
首先先来看字符流:
1.读取
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferReaderDemo { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileReader fr = new FileReader("E:\Text.txt"); BufferedReader bufr = new BufferedReader(fr);//把对象fr放入缓冲区 String line = null; while((line=bufr.readLine())!=null){ System.out.println(line); } bufr.close(); } }
2.写入
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferWrtierDemo { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter("E:\Text.txt"); //创建了一个字符写入流的缓冲区对象,并和指定要被缓冲的流对象相并联。 BufferedWriter bufw = new BufferedWriter(fw); //使用缓冲区的写入方法将数据先写入到缓冲区中。 bufw.write("abcdefg"); bufw.newLine();//写入一个行分隔符相当于"n""t" //使用缓冲区的率先呢方法将数据刷新到目的地中。 bufw.flush(); //关闭缓冲区。(其实关闭的就是被缓冲的流对象) bufw.close(); } }
上面都是字符流使用缓冲区的例子,而接下来我们来例举字节流使用缓冲区的效果。
字节流
1.读取
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; public class BufferedInputStream { /** * @param args * @throws IOException * @throws IOException * @throws Exception */ public static void main(String[] args) throws IOException, Exception{ FileInputStream fos = new FileInputStream("E:\Text.txt"); BufferedInputStream bufis = new BufferedInputStream(fos); int ch =0; while((ch=bufis.read())!=-1){ System.out.println((char)ch); } bufis.close(); } }
2.写入
import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class BufferedOutputStrem { /** * @param args * @throws IOException * @throws IOException * @throws Exception */ public static void main(String[] args) throws IOException, Exception{ FileOutputStream fos = new FileOutputStream("E:\Text.txt"); BufferedOutputStream bufos = new BufferedOutputStream(fos); //把数据写入到指定文件中 bufos.write("adcd".getBytes()); bufos.flush();//刷新数据,以备再次写入 bufos.write("abce".getBytes()); bufos.close(); } }
评论前必须登录!
注册