从资产复制到SD卡打开失败:ENOENT(没有此类文件或目录)

时间:2013-01-23 12:29:50

标签: android sd-card assets

我尝试从资产复制到SD卡 这是我的代码的一部分

private void CopyAssets(String folder) {

        File folders = new File(Environment.getExternalStorageDirectory().toString()+"/beatscache/"+folder);
        folders.mkdirs();
        AssetManager assetManager = getAssets();
        String[] files = null;
                try {
            files = assetManager.list(folder);
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }

        for(String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            try {
              in = assetManager.open(folder+"/"+filename);   // if files resides inside the "Files" directory itself
              out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/"+"beatscache"+"/"+folder +"/" + filename);
              copyFile(in, out);
              in.close();
              in = null;
              out.flush();
              out.close();
              out = null;
            } catch(Exception e) {
                Log.e("tag", e.getMessage());
            }
        }
    }
    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
          out.write(buffer, 0, read);
        }
    }

CopyAssets("bin");

日志显示

  

E / tag(3801):/ mnt / sdcard / beatscache / bin / alsa_ctl:open failed:ENOENT   (没有这样的文件或目录)

我在AndroidManifest.xml中给出了READ和WRITE权限 并检查Environment.MEDIA_MOUNTED.equals(state)是否返回true。

并没有创建文件夹。

你能说出我做错了吗?

1 个答案:

答案 0 :(得分:2)

首先检查文件是否存在,然后将内容移到那里

final File dir = new File(cEnvironment.getExternalStorageDirectory()+"/beatscache/"+folder +"/");
if(dir.exists()==false)
{
dir.mkdirs(); //create folders where write files
final File file = new File(dir, filename);
}