java——BufferedStream文件复制实例

如果您读取和写入的大小始终大于内部缓冲区的大小,那么 BufferedStream 可能甚至无法分配内部缓冲区。


首先新建一个类

public class zijieliu {

public static void main(String[] args) {}

}

在这个类中加入我们要写的copyfle方法

public void copyfile(String path, String newPath) {}

参数path为要进行复制的地址全路径,newPath为复制的目的地址全路径

为了创建BufferedInputstream,需要先创建InputStream对象,代码如下:

InputStream ins = null;
BufferedInputStream bis = null;

ins = new FileInputStream(path);
bis = new BufferedInputStream(ins);

同理,为了创建BufferedOutputstream,需要先创建outputStream对象,代码如下:

OutputStream ots = null;
BufferedOutputStream bos = null;

ots = new FileOutputStream(newPath);

bos = new BufferedOutputStream(ots);

利用BufferedStream的read()和write()方法进行文件读取操作,代码如下:

int in;
while ((in = bis.read()) != -1) {
bos.write(in);
}

为了使没有充满缓冲区时的数据也能被写入,使用flush()方法:

bos.flush();

在文件读取完成后,关闭所有的输入输出流:

if (bos != null)
bos.close();
if (bis != null)
bis.close();
if (ots != null)
ots.close();
if (ins != null)
ins.close();

这样,copyfile的方法就写好了,下面只需在主函数中创建对象,调用方法:

zijieliu a = new zijieliu();
a.copyfile("E://视频教程/1.1 前言-代码查看工具使用.wmv", "E://ins4.wmv");

最后贴上整体的代码图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值