Android:如何在SD卡上创建目录并将文件从/res/raw复制到其中?

标签 android

我正在尝试在 SD 卡上创建一个文件夹和其中的几个子目录...然后我想将我存储在/res/raw 中的文件传输到该文件夹​​...另外,我想要这个只发生一次,程序第一次运行。我意识到这是荒谬的开放式问题,而且我提出了很多要求...但我们将不胜感激任何帮助。

最佳答案

这会将 .apk Assets 文件夹的“clipart”子文件夹中的所有文件复制到 SD 卡上应用文件夹的“clipart”子文件夹中:

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    String basepath = extStorageDirectory + "/name of your app folder on the SD card";
//...

// in onCreate
File clipartdir = new File(basepath + "/clipart/");
        if (!clipartdir.exists()) {
            clipartdir.mkdirs();
            copyClipart();      
        }

private void copyClipart() {
        AssetManager assetManager = getResources().getAssets();
        String[] files = null;
        try {
            files = assetManager.list("clipart");
        } catch (Exception e) {
            Log.e("read clipart ERROR", e.toString());
            e.printStackTrace();
        }
        for(int i=0; i<files.length; i++) {
            InputStream in = null;
            OutputStream out = null;
            try {
              in = assetManager.open("clipart/" + files[i]);
              out = new FileOutputStream(basepath + "/clipart/" + files[i]);
              copyFile(in, out);
              in.close();
              in = null;
              out.flush();
              out.close();
              out = null;
            } catch(Exception e) {
                Log.e("copy clipart ERROR", e.toString());
                e.printStackTrace();
            }       
        }
    }
    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);
        }
    }

关于Android:如何在SD卡上创建目录并将文件从/res/raw复制到其中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3851712/

相关文章:

android - 仅使部分文本在 Android 中可编辑

java - 值(value)在方法途中丢失

java - 找不到哪里出错了

onDrawFrame 之外的 Android OpenGL 游戏循环

java - 如何修复[发现 : 'android.content.Context' , 需要 : 'androidx.lifecycle.LifecycleOwner' ] in BroadcastReceiver?

android - 简单的蓝牙数据接收器Android

android - 如何告诉 ORMLite 不要用 null 覆盖数据库中的值

java - 在 WebView DialogFragment 中触摸时不显示软键盘

android - 使用静态产品测试计费返回 SERVICE_DISCONNECTED

android - 如何在模拟器中安装 80 MB 大小的应用程序?