欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java中缓冲流

程序员文章站 2024-03-06 23:53:14
...

BufferedReader:从字符输入流读取文本,缓冲字符,以提供字符,数组和行的高效读取

其构造方法如下

java中缓冲流

其部分方法如下

java中缓冲流

java中缓冲流

这里以读取a.txt中的两行数据为例

import java.io.*;

public class Main {
    public static void main(String[] args) {
        File file = new File("C:\\Users\\Administrator\\Desktop\\a.txt");
        try {
            Reader in = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(in);
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                System.out.println(str);
            }
            in.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedWriter:将文本写入字符输出流,缓冲字符,以提供单个字符,数组和字符串的高效写入

其构造方法如下

java中缓冲流

其方法如下

java中缓冲流

这里以读取a.txt中的两行数据写入到b.txt为例

import java.io.*;

public class Main {
    public static void main(String[] args) {
        File file = new File("C:\\Users\\Administrator\\Desktop\\a.txt");
        File file1 = new File("C:\\Users\\Administrator\\Desktop\\b.txt");
        try {
            Reader in = new FileReader(file);
            Writer out  = new FileWriter(file1);
            BufferedReader bufferedReader = new BufferedReader(in);
            BufferedWriter bufferedWriter = new BufferedWriter(out);

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                bufferedWriter.write(str);
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}