學習java IO模塊寫的一個測試用例
Demo中有4個方法,在main方法中分別調用即可
在測試前請替換 源文件目錄
和目標文件目錄
package com.IOstream;
import java.io.*;
/**
* 字節流Demo 四種複製文件方式速度對比
* 方式1:字節流每次讀取一個字節
* 方式2:字節流每次讀取一個字節數組
* 方式3:字節緩衝流每次讀取一個字節
* 方式2:字節緩衝流每次讀取一個字節數組
*
*/
package com.IOstream;
import java.io.*;
/**
* 字節流Demo 四種複製文件方式速度對比
* 方式1:字節流每次讀取一個字節
* 方式2:字節流每次讀取一個字節數組
* 方式3:字節緩衝流每次讀取一個字節
* 方式2:字節緩衝流每次讀取一個字節數組
*/
public class IODemo02 {
static final String filePath1 = "源文件路徑";
static final String filePath2 = "目標文件路徑";
public static void main(String[] args) throws IOException {
// 記錄開始時間
long startTime = System.currentTimeMillis();
//copyFlies1(); 耗時 134931毫秒
//copyFlies2(); 耗時 205毫秒
//copyFlies3(); 耗時 346毫秒
//copyFlies4(); 耗時 47毫秒
// 記錄結束時間
long endTime = System.currentTimeMillis();
System.out.println("共耗時:" + (endTime - startTime) + "毫秒");
}
private static void copyFlies1() throws IOException {
FileInputStream fis = new FileInputStream(filePath1);
FileOutputStream fos = new FileOutputStream(filePath2);
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
}
// 關閉字節流,釋放系統資源
fis.close();
fos.close();
}
private static void copyFlies2() throws IOException {
FileInputStream fis = new FileInputStream(filePath1);
FileOutputStream fos = new FileOutputStream(filePath2);
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
// 關閉字節流,釋放系統資源
fis.close();
fos.close();
}
private static void copyFlies3() throws IOException {
FileInputStream fis = new FileInputStream(filePath1);
BufferedInputStream fbis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(filePath2);
BufferedOutputStream fbos = new BufferedOutputStream(fos);
int b;
while ((b = fbis.read()) != -1) {
fbos.write(b);
}
// 關閉字節緩衝流和字節流,釋放系統資源
fbis.close();
fbos.close();
fis.close();
fos.close();
}
private static void copyFlies4() throws IOException {
FileInputStream fis = new FileInputStream(filePath1);
BufferedInputStream fbis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(filePath2);
BufferedOutputStream fbos = new BufferedOutputStream(fos);
byte[] bytes = new byte[1024];
int len;
while ((len = fbis.read(bytes)) != -1) {
fbos.write(bytes, 0, len);
}
// 關閉字節流,釋放系統資源
fis.close();
fos.close();
}
}