从资产文件夹复制目录到数据文件夹。

10

我想在应用程序第一次运行时将一个很大的目录从我的应用程序资产文件夹复制到数据文件夹中。 我该怎么做? 我已经尝试了一些示例,但没有任何效果,因此我现在一无所获。 我的目标是Android 4.2。

谢谢, Yannik


你为什么要这样做?如果我没错的话,数据和资源文件夹将在应用程序安装期间一直存在。 - gunar
看一下这个,可能会对你们有用 https://dev59.com/7m855IYBdhLWcg3wQx5L#25988337 - DropAndTrap
2个回答

24

尝试使用您的应用实例中的此代码(您应该在清单中编写类): 此代码将assets/files文件夹的内容复制到应用程序的缓存文件夹中(您可以在copyAssetFolder()函数中放置其他路径)。仅当应用程序首次启动时。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.preference.PreferenceManager;

public class MyApplication extends Application {
    private static Context  s_sharedContext;

    @Override
    public void onCreate () {
        super.onCreate();   
        if (!PreferenceManager.getDefaultSharedPreferences(
                getApplicationContext())
            .getBoolean("installed", false)) {
            PreferenceManager.getDefaultSharedPreferences(
                    getApplicationContext())
                .edit().putBoolean("installed", true).commit();

            copyAssetFolder(getAssets(), "files", 
                    "/data/data/com.example.appname/files");
        }
    }

    private static boolean copyAssetFolder(AssetManager assetManager,
            String fromAssetPath, String toPath) {
        try {
            String[] files = assetManager.list(fromAssetPath);
            new File(toPath).mkdirs();
            boolean res = true;
            for (String file : files)
                if (file.contains("."))
                    res &= copyAsset(assetManager, 
                            fromAssetPath + "/" + file,
                            toPath + "/" + file);
                else 
                    res &= copyAssetFolder(assetManager, 
                            fromAssetPath + "/" + file,
                            toPath + "/" + file);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean copyAsset(AssetManager assetManager,
            String fromAssetPath, String toPath) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(fromAssetPath);
          new File(toPath).createNewFile();
          out = new FileOutputStream(toPath);
          copyFile(in, out);
          in.close();
          in = null;
          out.flush();
          out.close();
          out = null;
          return true;
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static 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);
        }
    }

}

谢谢,但我想把它放在数据文件夹里,因为我想运行文件夹内的脚本。 - yanniks
你指的是哪个文件夹?你能写出它的绝对路径吗? - matreshkin
例如 /data/data/com.example.appname/ - yanniks
1
据我所知,你无法这样做,但是你可以使用文件夹 /data/data/com.example.appname/files - 请查看更新的代码。 - matreshkin
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/31401/discussion-between-matreshkin-and-yanniks - matreshkin

1
private fun copyAssets(
    assetManager: AssetManager,
    assetPath: String,
    outputPath: String
) {
    // check if asset path is a file. if file exists, then it is copied to the output path
    try {
        // throws IOException when file does not exist
        val assetFd = assetManager.openFd(assetPath)
        // file exists, so file is copied to the output path
        copyFile(assetFd, outputPath)
    } catch (e: Exception) {
        try {
            // file does not exist
            // try to list asset path content
            val files = assetManager.list(assetPath)
            // create output directory if not exist
            val outputDir = File(outputPath)
            outputDir.mkdirs()
            // loop through asset path directory and copy content recursively
            files?.forEach { file ->
                // new asset path is set to file
                val newAssetPath = "$assetPath/$file"
                // set relative output file path
                val newOutputPath = "$outputPath/$file"
                // recursively copy from asset path to the output path
                copyAssets(assetManager, newAssetPath, newOutputPath)
            }
        } catch (e: java.lang.Exception) {
            // asset path is neither a file nor a directory
            throw IOException("asset path does not exist")
        }
    }
}

/**
 * copy file from asset file descriptor to the output file path
 */
private fun copyFile(inputFd: AssetFileDescriptor, outputFilePath: String) {
    val inputStream = inputFd.createInputStream()
    val outputStream = FileOutputStream(outputFilePath)
    val buffer = ByteArray(8192)
    var read = inputStream.read(buffer)
    while (read != -1) {
        outputStream.write(buffer, 0, read)
        read = inputStream.read(buffer)
    }
    inputStream.close()
    outputStream.close()
}

一个目录可以通过以下方式从assets复制到数据目录。
val assetPath = "resources"
val outputPath = "${appContext.filesDir.absolutePath}/resources"
val assetManager = appContext.resources.assets
copyAssets(assetManager, assetPath, outputPath)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接