2012-09-17 40 views
0

我有一個功能可以將存儲在資產中的JPEG複製到SD卡上。它工作,但非常非常緩慢。 averg文件大小約爲600k。有沒有更好的方式來做到這一點, 代碼:有沒有一種快速的方法將文件複製到SD卡

void SaveImage(String from, String to) throws IOException { 
    // opne file from asset 
    AssetManager assetManager = getAssets(); 
    InputStream inputStream; 
    try { 
    inputStream = assetManager.open(from); 
    } catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    return; 
    } 

    // Open file in sd card 
    String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
    OutputStream outStream = null; 
    File file = new File(extStorageDirectory, to); 
    try { 
    outStream = new FileOutputStream(file); 
    } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
    return; 
    } 

    int c; 
    while ((c = inputStream.read()) != -1) { 
    outStream.write(c); 
    } 

    outStream.close(); 
    inputStream.close(); 
    return; 
} 
+0

可能重複:http://stackoverflow.com/questions/4447477/android-how-to -copy-files-in-assets-to-sdcard –

回答

0

你應該使用BufferBufferedInputStreamBufferedOutputStream

InputStream inputStream; 
BufferedInputStream bis; 
try { 
    inputStream = assetManager.open(from); 
    bis = new BufferedInputStream(inputStream); 
} catch (IOException e) { 
... 
... 
try { 
    outStream = new BufferedOutputStream(new FileOutputStream(file)); 
} catch (FileNotFoundException e) { 
... 
... 
    while ((c = bis.read()) != -1) { 
    ... 
    } 
... 
... 

bis.close(); 

好運嘗試閱讀和寫作

+0

嗨,哇,什麼是速度差異,我認爲它會更復雜,然後加速它:) –

2

讀寫同時多個字符。儘管可以隨意嘗試,但16KB可能是一個合理的緩衝區大小。

+0

嗨,聽起來像一個很好的想法,我該怎麼做? –

+0

@Tedpottel:看到接受的答案在http://stackoverflow.com/questions/4447477/android-how-to-copy-files-in-assets-to-sdcard – CommonsWare

相關問題