簡體   English   中英

BufferedInputStream / BufferedOutputStream 的文件讀/寫速度

[英]Speed on file reading / writing by BufferedInputStream / BufferedOutputStream

有兩個問題。

  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();
    }
}

首先,您似乎只想按原樣復制文件。 有更簡單的(甚至可能是性能更高的方法)來做到這一點。

其他復制數據的方法

復制文件

如果您需要的只是復制示例中的實際文件,您可以簡單地使用:

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);
            }
        }
    }
}

深入描述您的問題

注意:我將籠統地談論InputStreamOutputStream 您使用BufferedInputStreamBufferedOutputStream 這些是內部緩沖數據的特定實現。 這個內部緩沖與我接下來要講的緩沖無關!

輸入流

InputStream#read()InputStream#read(byte[])之間存在根本區別。

InputStream#read()從 InputStream 中讀取一個字節並返回。 如果 Stream 已用盡(沒有更多數據),則返回值為0-255-1范圍內的int

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM