【问题标题】:Speed on file reading / writing by BufferedInputStream / BufferedOutputStreamBufferedInputStream / BufferedOutputStream 的文件读/写速度
【发布时间】:2021-05-07 11:46:26
【问题描述】:

有两个问题。

  1. 如果编码为 bis.read() 而不是 bis.read(bys),程序实际上会做什么? (它无论如何都可以工作,但速度要慢得多。)

  2. 为什么 bos.write(bys) 比 bos.write(bys, 0, len) 快得多? (我希望两者的运行速度相同。)

谢谢!

public class CopyFileBfdBytes {

    public static void main(String[] args) throws IOException {

        FileInputStream fis = new FileInputStream("d:/Test1/M1.MP3");
        BufferedInputStream bis = new BufferedInputStream(fis);

        FileOutputStream fos = new FileOutputStream("d:/Test2/M2.mp3");
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] bys = new byte[8192];
        int len;
        while ((len = bis.read(bys)) != -1){
//        while ((len = bis.read()) != -1){  // 1. Why does it still work when bys in bis.read() is missing?
            bos.write(bys);
//            bos.write(bys, 0, len);     // 2. Why is this slower than bos.write(bys)?
            bos.flush();
        }
        fis.close();
        bis.close();
        fos.close();
        bos.close();
    }
}

【问题讨论】:

  • bis.read() 不返回读取的字节数,而是返回一个字节,如果已达到 EOF,则表示为 0-255-1 范围内的 int。 bos.write(bys, 0, len) 并不慢,但你的 len 实际上不是长度
  • 1.所以 bis.read() 实际上是 bis.read(byte),对吧? 2. 如果我理解正确的话,当 byte[] bys = new byte[1024];, bos.write(bys, 0, len);当 byte[] bys = new byte[8192];, bos.write(bys); 时更快更快吧?
  • InputStream#read()InputStream#read(byte[]) 是从 InputStream 读取数据的完全不同的方法!第一个确实一次读取一个字节(它可能在内部使用缓冲区,但这取决于实现),第二个尝试将尽可能多的字节读取到指定的字节数组中。第一个返回已读取的实际字节数,第二个返回已读入指定数组的字节数。我会尽量给出更详细的答案

标签: java performance bufferedinputstream bufferedoutputstream


【解决方案1】:

首先,您似乎只想按原样复制文件。有很多更简单(甚至可能是性能更高的方法)来做到这一点。

其他复制数据的方法

复制文件

如果您需要的只是复制示例中的实际文件,您可以简单地使用:

package example;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        Files.copy(Paths.get("d:/Test1/M1.MP3"), Paths.get("d:/Test2/M2.mp3"));
    }
}

这很可能是最具描述性的(例如,其他开发人员实际上看到了您想要做什么),并且可以通过底层系统非常有效地完成。

将数据从任何来源复制到任何目的地(InputStream 到 OutputStream)

如果您需要将数据从任何 InputStream 传输到任何 OutputStream 您可以使用方法InputStream#transferTo(OutputStream):

package example;

import java.io.*;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        try (InputStream fis = new FileInputStream("d:/Test1/M1.MP3")) {
            try (OutputStream fos = new FileOutputStream("d:/Test2/M2.mp3")) {
                fis.transferTo(fos);
            }
        }
    }
}

深入描述您的问题

注意:我将笼统地谈论InputStreams 和OutputStreams。您使用了BufferedInputStreamBufferedOutputStream。这些是在内部缓冲数据的特定实现。这个内部缓冲与我接下来要讲的缓冲无关!

输入流

InputStream#read()InputStream#read(byte[]) 之间存在根本区别。

InputStream#read() 从 InputStream 中读取一个字节并返回。如果 Stream 已用尽(没有更多数据),则返回值为int,范围为0-255-1

package example;

import java.io.*;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1, 0, 3, 4, 5, 6, 7, 8, 127};
        printAllBytes(new ByteArrayInputStream(myBytes));
    }

    public static void printAllBytes(InputStream in) throws IOException {
        int currByte;
        while ((currByte = in.read()) != -1) {
            System.out.println((byte) currByte);// note the cast to byte!
        }
        
        // prints: -1, 0, 3, 4, 5, 6, 7, 8, 127
    }
}

InputStream#read(byte[]) 然而,完全不同。它采用byte[] 作为参数,用作缓冲区。然后它(在内部)尝试用它目前可以获得的尽可能多的字节填充给定的缓冲区,并返回它已填充的实际字节数,如果 Stream 已用尽,则返回 -1

例子:

package example;

import java.io.*;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1, 0, 3, 4, 5, 6, 7, 8, 127};
        printAllBytes(new ByteArrayInputStream(myBytes));
    }

    public static void printAllBytes(InputStream in) throws IOException {
        final byte[] buffer = new byte[2];// do not use this small buffer size. This is just for the example
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            // loop from 0 to bytesRead, !NOT! to buffer.length!!!
            for (int i = 0; i < bytesRead; i++) {
                System.out.println(buffer[i]);
            }
        }

        // prints: -1, 0, 3, 4, 5, 6, 7, 8, 127
    }
}

不好的例子: 现在是一个不好的例子。以下代码包含编程错误,请勿使用!

我们现在从0 循环到buffer.length,但我们的输入数据正好包含9 字节。这意味着,在最后一次迭代中,我们的缓冲区只会被一个字节填充。我们缓冲区中的第二个字节不会被触及。

package example;

import java.io.*;

public class SO66024231 {

    /**
     * ERROURNOUS EXAMPLE!!! DO NOT USE
     */
    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1, 0, 3, 4, 5, 6, 7, 8, 127};
        printAllBytes(new ByteArrayInputStream(myBytes));
    }

    public static void printAllBytes(InputStream in) throws IOException {
        final byte[] buffer = new byte[2];// do not use this small buffer size. This is just for the example
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            for (int i = 0; i < buffer.length; i++) {
                System.out.println(buffer[i]);
            }
        }

        // prints: -1, 0, 3, 4, 5, 6, 7, 8, 127, 8 <-- see; the 8 is printed because we ignored the bytesRead value in our for loop; the 8 is still in our buffer from the previous iteration
    }
}

输出流

既然我已经描述了阅读的差异是什么,那么我将向您描述写作的差异。

首先,正确的例子(使用OutputStream.write(byte[], int, int)):

package example;

import java.io.*;
import java.util.Arrays;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1, 0, 3, 4, 5, 6, 7, 8, 127};
        final byte[] copied = copyAllBytes(new ByteArrayInputStream(myBytes));

        System.out.println(Arrays.toString(copied));// prints: [-1, 0, 3, 4, 5, 6, 7, 8, 127]
    }

    public static byte[] copyAllBytes(InputStream in) throws IOException {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final byte[] buffer = new byte[2];
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }

        return bos.toByteArray();
    }
}

还有一个不好的例子:

package example;

import java.io.*;
import java.util.Arrays;

public class SO66024231 {

    /*
    ERRORNOUS EXAMPLE!!!!
     */
    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1, 0, 3, 4, 5, 6, 7, 8, 127};
        final byte[] copied = copyAllBytes(new ByteArrayInputStream(myBytes));

        System.out.println(Arrays.toString(copied));// prints: [-1, 0, 3, 4, 5, 6, 7, 8, 127, 8] <-- see; the 8 is here again
    }

    public static byte[] copyAllBytes(InputStream in) throws IOException {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final byte[] buffer = new byte[2];
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            bos.write(buffer);
        }

        return bos.toByteArray();
    }
}

这是因为,就像在我们的 InputStream 示例中一样,如果我们忽略 bytesRead,我们将向 OutputStream 写入一个我们不想要的值:字节 8 来自以前的迭代。这是因为在内部,OutputStream#write(byte[])(在大多数实现中)只是OutputStream.write(buffer, 0, buffer.length) 的快捷方式。这意味着它将整个缓冲区写入OutputStream

【讨论】:

  • 感谢开发者!稍后我会仔细研究它,当我在您的宝贵帮助下得到进一步澄清时,我会回来。再次感谢!
  • 您不需要嵌套的 try 块。单个try 可以处理多个资源,即try(InputStream fis = new FileInputStream("d:/Test1/M1.MP3"); OutputStream fos = new FileOutputStream("d:/Test2/M2.mp3")) { fis.transferTo(fos); }
猜你喜欢
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 2011-08-13
  • 2014-12-02
  • 1970-01-01
  • 2012-03-14
  • 2017-12-07
  • 2014-10-05
相关资源
最近更新 更多