如果您读取和写入的大小始终大于内部缓冲区的大小,那么 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");
最后贴上整体的代码图: