2014-03-12 78 views
1

我使用此代碼,但它在文件outputstream處失敗。 當我做一個靜態無效然後getResources將失敗。從原始文件夾複製圖像到外部SD卡?

public void copy (Context context) { 
InputStream in = getResources().openRawResource(R.raw.high1); 
FileOutputStream out = new FileOutputStream("/sdcard/pic1.jpg"); 
byte[] buff = new byte[1024]; 
int read = 0; 

try { 
    while ((read = in.read(buff)) > 0) { 
     out.write(buff, 0, read); 
    } 
} finally { 
    in.close(); 

    out.close(); 
} 

}

+1

**永遠不用硬編碼PATHS **。使用'getExternalFilesDir()'或'Environment.getExternalStoragePublicDirectory()'或類似的東西來獲取外部存儲上的目錄。 – CommonsWare

回答

0

要getResources()將其更改爲靜態時不會失敗,修改線:

的InputStream在= getResources()openRawResource(R.raw.high1) ;

到:

的InputStream在= context.getResources()openRawResource(R.raw.high1);

此外,引用CommonsWare:

NEVER硬編碼路徑。使用getExternalFilesDir()或Environment.getExternalStoragePublicDirectory()或類似的東西來獲取外部存儲上要使用的目錄。

相關問題