gpt4 book ai didi

Android - 将文件从 Assets 复制到/数据/数据文件夹

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:00:34 25 4
gpt4 key购买 nike

我需要在我的应用程序中使用一些文件。它们保存在 Assets 文件夹中。我看到了关于 SO 的讨论,其中文件从 Assets 文件夹复制到内部存储上的/data/data/ ,然后被使用。我得到了代码,但我不明白的是,将 Assets 复制到内部存储有什么用?

最佳答案

试试这个:(使用所有这三种方法对我有用,并在“toPath”字符串对象中分配目标路径)

  String toPath = "/data/data/" + getPackageName();  // Your application path


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

关于Android - 将文件从 Assets 复制到/数据/数据文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com