【发布时间】:2021-08-20 14:02:03
【问题描述】:
我正在学习 Java I/O,我对以下两个复制文件的 sn-ps 之间的差异有疑问:
片段 1,使用 FileInput/OutputStream 和字节数组:
public static void main(String[] args) throws IOException {
//function: copy a jpg file
//1.get a jpg as source file
File f1 = new File("d:\\LOL.jpg");
//2.get a target file
File f2 = new File("d:\\LOL2.jpg");
//3.using FileInputStream for source file
FileInputStream fis = new FileInputStream(f1);
//4.using FileOutputStream for target file
FileOutputStream fos = new FileOutputStream(f2);
//5.copy the file by byte array
byte[] b = new byte[1024*8];
int len = fis.read(b);
while(len!=-1){
fos.write(b,0,len);
len = fis.read(b);
}
//6.close stream
fos.close();
fis.close();
}
片段 2,使用 BufferedInput/OutputStream
public static void main(String[] args) throws IOException {
//1.get a jpg as source file
File f1 = new File("d:\\LOL.jpg");
//2.get a target file
File f2 = new File("d:\\LOL2.jpg");
//3.using FileInputStream for source file
FileInputStream fis = new FileInputStream(f1);
//4.using FileOutputStream for target file
FileOutputStream fos = new FileOutputStream(f2);
//5.use BufferedInputStream:
BufferedInputStream bis = new BufferedInputStream(fis);
//6.use BufferedOutputStream:
BufferedOutputStream bos = new BufferedOutputStream(fos);
//7.copy
byte[] b = new byte[1024*8];
int len = bis.read(b);
while(len!=-1){
bos.write(b,0,len);
len = bis.read(b);
}
//8.close
bos.close();
bis.close();
我查看了BufferedInput/OutputStream的源码,发现它的默认缓冲区大小是1024*8字节
我的困惑是:
-
BufferedInput/OutputStream 中的内部缓冲区实际上是做什么的?是不是和sn-p 1中的字节数组的作用一样?
-
如果他们扮演同样的角色,那么为什么 BufferedInput/OutputStream 更高效?
【问题讨论】:
-
@user16320675 我测量了这两种方法的时间。
-
@user16320675 我测试了我的代码,如果我将两个字节数组都设置为 1024,那么缓冲 I/O 会快得多,但如果我将两个字节数组都设置为 8192,那么它们就是几乎相同,文件 I/O 流甚至可以快 1 毫秒。是不是因为缓冲 I/O 实际上使用了内部缓冲区以及字节数组,而文件 I/O 只使用了字节数组?