package xyz.jangle.io.buffered;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 比较有bufferedOutputStream和无bufferedOutputStream 但使用byte[8192]的字节数组的写入速度
* @author jangle
* @email 274676957@qq.com
* 2026年1月4日 下午1:21:56
*/
public class CompareBuffered {
/**
* 2026年1月4日 下午1:21:56 @author jangle
* @param args
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();
writeNotWithBuffer(); //370ms 63011ms
// writeWithBuffer(); //406ms 66492ms
long end = System.currentTimeMillis();
System.out.println(end-start);
}
private static void writeWithBuffer() {
try(InputStream fis = new FileInputStream("D:/d/test10.rar");
OutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/d/testCompare1.rar"))){
byte[] buf = new byte[8192];
int len;
while((len = fis.read(buf)) != -1) {
bos.write(buf, 0, len);
}
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeNotWithBuffer() {
try(InputStream fis = new FileInputStream("D:/d/test10.rar");
OutputStream fos = new FileOutputStream("D:/d/testCompare2.rar")){
byte[] buf = new byte[8192];
int len;
while((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
单纯文件流的耗时比缓冲流的耗时少(4GB文件,单纯文件流耗时63011ms,缓冲流耗时66492ms),有两个原因:
1、缓冲区设置得和缓冲流(BufferedOutputStream)内置缓存(8192)一样大,则缓冲流没有优势,反而还多了1次内存的拷贝。
2、缓冲流的write方法有synchronized修饰,而文件流没有。多了同步的开销。
2845

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



