【问题标题】:Android: How to create a directory on the SD Card and copy files from /res/raw to it?Android:如何在 SD 卡上创建目录并将文件从 /res/raw 复制到该目录?
【发布时间】:2010-10-03 21:41:28
【问题描述】:

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

【问题讨论】:

    标签: android


    【解决方案1】:

    这会将 .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);
            }
        }
    

    【讨论】:

    • 这段代码需要在哪里确保它只发生一次,在安装时,然后从 APK 中删除文件?
    • @joon:您可以使用link 保存一个布尔值,以确保它只发生一次。顺便说一句,你不能从 apk 中删除文件。@查看更多:link
    【解决方案2】:

    我在使用 mkdirs() 时遇到了类似的问题,但是因为运行命令:

    mkdir 一/二

    在 Linux 上失败,然后方法 http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdirs() 随后也失败。我想这意味着没有办法在 Android 上使用 mkdirs?我(可能相当老套)的解决方法是分别创建每个必要的目录:

    String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    new File(extStorageDirectory + "/one/").mkdirs();
    new File(extStorageDirectory + "/one/two/).mkdirs();
    

    【讨论】:

    • File.mkDirs() 有效。我已经在 Android 2.1(API 级别 7)上尝试过