字符缓冲流BufferedReader/BufferedWriter

字符缓冲流

BufferedReader/BufferedWriter

字符缓冲流使得字符的能够高效的读取和写出

1、缓冲字符输入流BufferedReader

import java.io.*;
/**
 * 缓冲字符输入流BufferedReader
 * 文件字符输入流,加入缓冲流
 * 1、创建源
 * 2、选择流
 * 3、操作
 * 4、释放资源
 */
public class BufferedTest03 {
    public static void main(String[] args) {
        //1、创建源
        File src = new File("abc.txt");
        //2、选择流
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new FileReader(src));
            String line = null;
            while((line = reader.readLine())!=null){
                //字符数组->字符串
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //4、释放资源
            if (reader != null) {
                try{
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2、缓冲字符输出流BufferedWriter

import java.io.*;
/**
 * 缓冲字符输出流BufferedWriter
 * 文件字符输出流,加入缓冲流
 * 1、创建源
 * 2、选择流
 * 3、操作
 * 4、释放资源
 */
public class BufferedTest04 {
    public static void main(String[] args) {
        //1、创建源
        File src = new File("dest.txt");
        //2、选择流
        BufferedWriter writer = null;
        try{
            writer = new BufferedWriter(new FileWriter(src));
            String msg = "IO is so easy\r\n北京欢迎你\r\n我爱我家";
            char[] datas = msg.toCharArray();
            writer.write(datas,0,datas.length);
            writer.newLine();//换行
            writer.write("haha");
            writer.newLine();
            writer.append("dada");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //4、释放资源
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

你可能感兴趣的:(字符缓冲流BufferedReader/BufferedWriter)