java IO流之三 使用缓冲流来读写文件

时间:2025-02-21 21:16:35

一、通过BufferedReader和BufferedWriter来读写文件

     使用缓冲流的好处是,能够更高效的读写信息,原理是将数据先缓冲起来,然后一起写入或者读取出来。经常使用的是readLine()方法,表示一次读取一行数据。

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class TestBufferedWriter {

    public static void main(String[] args) throws Exception {
        write();
        read();
    }

    /**
     * DOC 读取信息.
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void read() throws FileNotFoundException, IOException {
        File file = new File("E:\\");// 指定要读取的文件
        // 获得该文件的缓冲输入流
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String line = "";// 用来保存每次读取一行的内容
        while ((line = ()) != null) {
            (line);
        }
        ();// 关闭输入流
    }

    /**
     * DOC 写入信息.
     * 
     * @throws IOException
     */
    private static void write() throws IOException {
        File file = new File("E:\\");// 指定要写入的文件
        if (!()) {// 如果文件不存在则创建
            ();
        }
        // 获取该文件的缓冲输出流
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
        // 写入信息
        ("你好世界");
        ();// 表示换行
        ("hello world");
        ();// 清空缓冲区
        ();// 关闭输出流
    }

}

二、使用BufferedInputStream和BufferedOuputStream读写图片

使用方式和FileInputStrem和FileOutputStream基本一致:

package ;

import ;
import ;
import ;
import ;
import ;

public class TestBufferedString {

    public static void main(String[] args) throws Exception {
        // 指定要读取文件的缓冲输入字节流
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("F:\\"));
        File file = new File("E:\\");
        if (file != null) {
            ();
        }
        // 指定要写入文件的缓冲输出字节流
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        byte[] bb = new byte[1024];// 用来存储每次读取到的字节数组
        int n;// 每次读取到的字节数组的长度
        while ((n = (bb)) != -1) {
            (bb, 0, n);// 写入到输出流
        }
        ();// 关闭流
        ();
    }

}