java 缓存输入输出流

来源:互联网 发布:python inceptor 编辑:程序博客网 时间:2024/05/17 17:40

package com.cool.io;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class BufferInputStreamTest {    public static void main(String[] args) {        File file = new File("D:" + File.separator + "123.txt");        FileInputStream fin = null;        BufferedInputStream bin = null;        FileOutputStream fout = null;        BufferedOutputStream bout = null;        try {            fin = new FileInputStream(file);            bin = new BufferedInputStream(fin);            fout = new FileOutputStream("D:" + File.separator + "123copy.txt");            bout = new BufferedOutputStream(fout);            byte[] b = new byte[2048];            int len;            while (0 < (len = bin.read(b))) {                bout.write(b, 0, len);            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (fout != null) {                    bout.flush();//在关闭前调用,避免缓存数据没及时写到文件里                    fout.close();                }                if (bout != null) {                    bout.close();                }                if (fin != null) {                    fin.close();                }                if (bin != null) {                    bin.close();                }            } catch (IOException e) {            }        }    }}

1.功能:给文件的读写加上缓存,使之更搞笑

2.注意:输出流close时,调用flush,清空缓存上的字节。

0 0
原创粉丝点击