2014-03-25 30 views
3

我有3236000個字節的文件,我想從開始讀2936000和寫入到OutputStream的Java複製InputStream的一部分的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 */ 

我可以讀取和字節寫字節,但它是慢(我認爲)從緩衝讀數 如何複製它?

+0

這是什麼問題? – Shawn

+0

我想將InputStream的一部分複製到OutputStream – Curious

回答

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

應該爲你工作。

+0

bytesRead <=結束只是在步驟重新加入的字節<=結束而不是結束所有加入的字節時檢查。 – Curious

+0

是@Curious它將處理第一個字節,然後使用1024字節的緩衝區寫入輸出流您也可以查看Channel類。 – nimsson

相關問題