在进行文件 IO 处理的时候,使用合适的缓冲区可以明显提高性能
测试
//使用BufferedInputStream和BufferedOutputStream
private static void bufferedStreamByteOperation() throws IOException {
try(BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File("")));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("")));){
int i;
while ((i = bufferedInputStream.read()) != -1) {
bufferedOutputStream.write(i);
}
}
}
//额外使用一个8KB缓冲,再使用BufferedInputStream和BufferedOutputStream
private static void bufferedStreamBufferOperation() throws IOException {
try(BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File("")));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("")));){
byte[] buffer = new byte[8192];
int len = 0;
while ((len = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, len);
}
}
}
//直接使用FileInputStream和FileOutputStream,再使用一个8KB的缓冲
private static void largerBufferOperation() throws IOException {
try(FileInputStream fileInputStream = new FileInputStream("");
FileOutputStream fileOutputStream = new FileOutputStream("");){
byte[] buffer = new byte[8192];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
}
}
测试结果
1424649223 086% bufferedStreamByteOperation
117807808 007% bufferedStreamBufferOperation
112153174 007% largerBufferOperation
可以看到,第一种方式虽然使用了缓冲流,但逐字节的操作因为方法调用次数实在太多还是慢,耗时 1.4 秒;后面两种方式的性能差不多,耗时 110 毫秒左右。虽然第三种方式没有使用缓冲流,但使用了 8KB 大小的缓冲区,和缓冲流默认的缓冲区大小相同。
流式复制
对于类似的文件复制操作,如果希望有更高性能,可以使用FileChannel 的 transfreTo 方法进行流的复制。在一些操作系统(比如高版本的 Linux 和UNIX)上可以实现 DMA(直接内存访问),也就是数据从磁盘经过总线直接发送到目标文件,无需经过内存和 CPU 进行数据中转:
private static void fileChannelOperation() throws IOException {
FileChannel in = FileChannel.open(Paths.get("src.txt"), READ);
FileChannel out = FileChannel.open(Paths.get("dest.txt"), CREATE, WRITE);
in.transferTo(0, in.size(), out);
}
本文探讨了在Java中如何通过使用BufferedInputStream、BufferedOutputStream和FileChannel来提升文件IO操作的性能。测试结果显示,使用缓冲区和FileChannel的transfersTo方法能显著减少操作时间,尤其是在大型数据传输中。直接使用BufferedInputStream和BufferedOutputStream的字节操作由于方法调用频繁而较慢,而结合8KB缓冲区的两种方法表现相近,都在110毫秒左右。FileChannel的transferTo方法在某些系统上甚至可以实现DMA,避免CPU参与数据中转,进一步提高效率。
3636

被折叠的 条评论
为什么被折叠?



