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。
建議採用數組的讀取方式,這種更快。