2014-03-12 80 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()或类似的东西来获取外部存储上要使用的目录。

相关问题