------- android培训、java培训、期待与您交流! ----------
//复制一文件,比较两个复制快慢
import java.io.*;
class CopyPic
{
public static void main(String[] args)
{
FileOutputStream fos = null;
FileInputStream fis = null;
try
{
long start = System.currentTimeMillis();
//方法一
fis = new FileInputStream("d:\\1.rar");
fos = new FileOutputStream("d:\\2.rar");
byte [] buf = new byte[1024*1024];
int len = 0;
while ((len = fis.read(buf))!=-1)
{
fos.write(buf,0,len);
}
//方法二
/*fis = new FileInputStream("d:\\1.rar");
fos = new FileOutputStream("d:\\2.rar");
int num = fis.available();
byte [] buf = new byte[num];
fis.read(buf);
fos.write(buf,0,num);
*/
long end = System.currentTimeMillis();
System.out.println("复制时间:"+(end-start));
}
catch (IOException e)
{
throw new RuntimeException("复制文件失败");
}
finally
{
try
{
if(fos!=null)
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("读取文件关闭失败");
}
try
{
if(fis!=null)
fis.close();
}
catch (IOException e)
{
throw new RuntimeException("复制文件关闭失败");
}
}
}
}
使用方法的结果
使用方法二的结果
如果把方法一中的数组大小定义为1024*1024结果为
但是如果把数组大小调整为1024*1024*30结果又会重新变大
long start = System.currentTimeMillis();
BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("d:\\1.rar"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("d:\\2.rar"));
int by =0;
while ((by=bufis.read())!=-1)
{
bufos.write(by);
}
使用缓冲区会时速度更慢