缓冲流效率测试
- 查询 API,缓冲流读写方法与基本的流是一致的,我们通过复制大文件(375 MB),测试它的效率;
1. 基本流
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
long start = System.currentTimeMillis();
try (
FileInputStream fis = new FileInputStream("jdk8.exe");
FileOutputStream fos = new FileOutputStream("copy.exe")
) {
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("普通流复制时间:" + (end - start) + " 毫秒");
}
}
2. 缓冲流
import java.io.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
long start = System.currentTimeMillis();
try (
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("jdk8.exe"));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("copy.exe"));
) {
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("缓冲流复制时间:" + (end - start) + " 毫秒");
}
}
- 缓冲流复制时间:8016 毫秒;
- 如何更快呢?我们可以使用数组的方式:
import java.io.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
long start = System.currentTimeMillis();
try (
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("jdk8.exe"));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("copy.exe"));
) {
int len;
byte[] bytes = new byte[8 * 1024];
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("缓冲流使用数组复制时间:" + (end - start) + " 毫秒");
}
}
3. 结论
- 缓冲流比传统的流效率更高,并且用数组的方式传输更快;