如何将Assets文件夹复制到内部存储?

时间:2019-06-23 22:29:00

标签: java android android-studio

我从这里复制了许多可能的解决方案,而我没有成功。我尝试将资产文件夹复制到存储数据,但是在尝试复制资产数据后总是出现日志错误

private void copyAssets() {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list("");
        } catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }
        for(String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            Toast.makeText(this, ""+filename, Toast.LENGTH_LONG).show();
            try {
                in = assetManager.open(filename);
                //File outFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationInfo().packageName+"/", filename);
                File outFile = new File(Environment.getExternalStorageDirectory()+"/osmdroid/", filename);
                out = new FileOutputStream(outFile);
                //out = new FileOutputStream(outFile);
                copyFile(in, out);
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch(IOException e) {
                Log.e("tag", "Failed to copy asset file: " + filename, e);
            }
        }
    }
    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);
        }
    }

请问,有关此错误的任何信息吗?

06-23 18:06:06.316 10803-10803/com.restaurantesencuba.myapplication E/tag: Failed to copy asset file: images
    java.io.FileNotFoundException: images

1 个答案:

答案 0 :(得分:0)

我遇到了完全相同的错误,实际上在调试时我发现了“图像”,“声音”和“ webkit”,所以看来您应该跳过不存在的图像,因为没有其他方法可以检查它们存在:

AssetManager assetManager = context.getAssets();
String[] files;
try {
    files = assetManager.list("");
} catch (IOException e) {
    Log.e("tag", "Failed to get asset file list.", e);
    return;
}
for(String filePath : files) {
    try {
        InputStream in = assetManager.open(filePath);
        //do your work...
    } catch (IOException ignored) { }
}