簡體   English   中英

Java 將 InputStream 的一部分復制到 OutputStream

[英]Java copy part of InputStream to OutputStream

我有一個 3236000 字節的文件,我想從頭開始讀取 2936000 並寫入一個 OutputStream

InputStream is = new FileInputStream(file1);
OutputStream os = new FileOutputStream(file2);

AFunctionToCopy(is,os,0,2936000); /* a function or sourcecode to write input stream 0to2936000 bytes */

我可以逐字節讀取和寫入,但是緩沖讀取會減慢(我認為)如何復制它?

public static void copyStream(InputStream input, OutputStream output, long start, long end)
    throws IOException
{
    for(int i = 0; i<start;i++) input.read(); // dispose of the unwanted bytes
    byte[] buffer = new byte[1024]; // Adjust if you want
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1 && bytesRead<=end) // test for EOF or end reached
    {
        output.write(buffer, 0, bytesRead);
    }
}

應該適合你。

如果您有權訪問 Apache Commons 庫,則可以使用:

IOUtils.copyLarge(InputStream input, OutputStream output, long inputOffset, long length)

暫無
暫無

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

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