本文实例为大家分享了 java 使用 缓冲流 复制文件 的具体代码,供大家参考,具体内容如下
[1] 程序设计
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
/*------------------------------- 1.缓冲流是一种处理流,用来加快节点流对文件操作的速度 2.bufferedinputstream:输入缓冲流 3.bufferedoutputstream:输出缓冲流 4.在正常的java开发中都使用缓冲流来处理文件,因为这样可以提高文件处理的效率 5.这里设计程序:使用缓冲流复制一个较大的视频文件 --------------------------------*/ package pack04;
import java.io.*;
public class copyfile {
public static void main(string[] args) {
string src = "d:/test/加勒比海盗-黑珍珠号的诅咒.rmvb" ; //源文件路径,该文件大小为3.01gb string dst = "d:/test/加勒比海盗-黑珍珠号的诅咒-java复制.rmvb" ; //目标文件路径
long starttime = system.currenttimemillis(); //获取复制前的系统时间 copy(src, dst); long endtime = system.currenttimemillis(); //获取复制后的系统时间
system.out.println( "spend time: " + (endtime-starttime) ); //输出复制需要的时间,毫秒计
}
//定义一个用于复制文件的静态方法,参数src代表源文件路径,参数dst代表目标文件路径 public static void copy(string src, string dst) {
//提供需要读入和写入的文件 file filein = new file(src); file fileout = new file(dst);
bufferedinputstream bis = null ; bufferedoutputstream bos = null ;
try {
//创建相应的节点流,将文件对象作为形参传递给节点流的构造器 fileinputstream fis = new fileinputstream(filein); fileoutputstream fos = new fileoutputstream(fileout);
//创建相应的缓冲流,将节点流对象作为形参传递给缓冲流的构造器 bis = new bufferedinputstream(fis); bos = new bufferedoutputstream(fos);
//具体的文件复制操作 byte [] b = new byte [ 65536 ]; //把从输入文件读取到的数据存入该数组 int len; //记录每次读取数据并存入数组中后的返回值,代表读取到的字节数,最大值为b.length;当输入文件被读取完后返回-1 while ( (len=bis.read(b)) != - 1 ) { bos.write(b, 0 , len); bos.flush(); }
} catch (ioexception e) {
e.printstacktrace();
} finally {
//关闭流,遵循先开后关原则(这里只需要关闭缓冲流即可) try { bos.close(); } catch (ioexception e) { e.printstacktrace(); }
try { bis.close(); } catch (ioexception e) { e.printstacktrace(); } } } } |
[2] 测试结果
测试结果显示,复制3.01gb大小的文件所用的时间约为1min。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://www.cnblogs.com/EarthPioneer/p/9363289.html
查看更多关于java使用缓冲流复制文件的方法的详细内容...