1.字节缓冲流
- 原理:字节缓冲输入流自带8KB缓冲池;字节缓冲输出流自带8KB缓冲池
public static void main(String[] args) throws IOException {try(InputStream is = new FileInputStream("D:\\pt\\123.jpg");//1.定义一个字节缓冲输入流包装原始的字节输入流InputStream bis = new BufferedInputStream(is,8192 * 2);OutputStream os = new FileOutputStream("C:\\hhh\\123.jpg");//2.定义一个字节缓冲输出流包装原始的OutputStream bos = new BufferedOutputStream(os,8192 * 2);){byte[] buffer = new byte[1024];int len;//记住每次读取了多少个字节while ((len = bis.read(buffer)) != -1){bos.write(buffer,0,len);}System.out.println("复制完成!");} catch (FileNotFoundException e) {e.printStackTrace();}}
2.字符缓冲流
BufferedReader(字符缓冲输入流)
- 作用:自带8K的字符缓冲池,可以提高字符输入流读取字符数据的性能
public static void main(String[] args) {try (FileReader fr = new FileReader("src/666.txt");//创建一个字符缓冲输入流包装原始的字符输入流BufferedReader br = new BufferedReader(fr)){
// char[] buffer = new char[3];
// int len;
// while ((len = fr.read(buffer)) != -1){
// System.out.println(new String(buffer, 0, len));
// }
// System.out.println(br.readLine());
// System.out.println(br.readLine());
// System.out.println(br.readLine());String line; //记住每次读取的一行数据while ((line = br.readLine()) != null){System.out.println(line);}} catch (IOException e) {e.printStackTrace();}}
BufferedWriter(字符缓冲输出流)
public static void main(String[] args) {try (Writer fw = new FileWriter("src/666.txt",true);//BufferedWriter bw = new BufferedWriter(fw);){fw.write("123");fw.write("6");fw.write("wcw");bw.newLine();//换行fw.write("123");fw.write('a');bw.newLine();} catch (IOException e) {e.printStackTrace();}}
3.案例:恢复文本的序号顺序到新文件中
public static void main(String[] args) {try (BufferedReader br = new BufferedReader(new FileReader("src/666.txt"));BufferedWriter bw = new BufferedWriter(new FileWriter("src/123.txt"));){//1.定义一个ArrayList集合存放每段内容List<String> data = new ArrayList<>();//2.按照每行读取内容,存入到集合String line;while((line = br.readLine()) != null){data.add(line);}//3.进行排序Collections.sort(data);System.out.println(data);//4.遍历集合存入到新文件for (String l : data) {bw.write(l);bw.newLine();}} catch (IOException e) {e.printStackTrace();}}