public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("D:\\1upload\\121.rar");
FileOutputStream fos2 = new FileOutputStream("D:\\1upload\\213.rar");
//方法二: 效率高,一次整个数组
byte[] bytes = new byte[1024];
int len = 0;
long s2 = System.currentTimeMillis();
while ((len = fis.read(bytes)) != -1) {
fos2.write(bytes, 0, len);
}
long e2 = System.currentTimeMillis();
System.out.println("一次读一个数组花费时间" + (e2-s2));
fis.close();
fos.close();
}
测试结果:
一次读取一个1024长度的数组。
121.rar文件大概76M左右,采用数据的读取方式花费时间为789ms。
我们试下一个字节一个字节读试下:
public static void main(String[] args) throws Exception {
System.out.println("流测试开始!!!!!");
FileInputStream fis = new FileInputStream("D:\\1upload\\121.rar");
FileOutputStream fos = new FileOutputStream("D:\\1upload\\214.rar");
int b = 0;
long s1 = System.currentTimeMillis();
while ((b = fis.read()) != -1) {
fos.write(b);
}
long e1 = System.currentTimeMillis();
System.out.println("一次读一个字节时间:"+ (e1 - s1));
fis.close();
fos.close();
}
测试结果:
测试结果大大的出乎意料,实在差距太大了,采用数组方式的只用了789ms 而单个读取的用了424s。
建议采用数组的读取方式,这种更快。