【Java IO】带缓冲的任意文件的复制

/**
 * 带缓冲功能(缓冲大小8K)的任意文件的复制(字节流)
 * @author MJN
 * @date   2011-10-03
 */
public class FileCopyWithBuffer {

    public static void main(String[] args) {
        InputStream in = null;
        OutputStream out = null;
        byte[] buf = new byte[8 * 1024];
        int n = -1;     //记录每次读取的实际字节长度
        try {
            in = new FileInputStream("1.jpg");      //文件1.jpg在工程的根目录下
            out = new FileOutputStream("1_copy.jpg");
            while ((n = in.read(buf)) != -1) {
                /*
                 * 若写成out.write(buf), 则最后一次写入的总是8K字节
                 * 即使最后一次读的字节数不一定为8K
                 */
                out.write(buf, 0, n);
            }
        } catch (FileNotFoundException e) {
            System.out.println("file not found.");
        } catch (IOException e) {
            System.out.println("error happened.");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {}
        }
    }
}

另外, 若要缓冲读取文件也可以用BufferedInputStream:

        InputStream in = new BufferedInputStream(
                new FileInputStream("in.txt"), 8 * 1024);

注意: 初始化时, 缓冲大小最好是1024的整数倍, 以使底层的操作达到最优化.

References:

NNU姜老师的课堂源码'java_course'

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值