【发布时间】:2021-01-19 14:29:23
【问题描述】:
所以意图很简单,我想将文件从 APK 的资产文件夹复制到设备存储。我通过下面的代码实现了这一点,它实际上正在工作,
public void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = getAssets().list("sourcedir");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "TargetFol");
if (!folder.exists()) {
folder.mkdirs();
}
File outFile = new File(folder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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);
}
}
getAssets().list("sourcedir") 实际上列出了APK的assets文件夹中sourcedir中的所有图片。
但是当调用它的方法时,它只对少数文件抛出FileNotFoundException: myfile.png。
比如我在sourcedir中放了5个png (1.png, 2.png, 3.png, myfile.png, zip.png) 除了myfile.png之外的所有文件都复制了
我确认没有不同的扩展或者我已经分析了 APK 并且所有这 5 个图像实际上都在 assets/sourcedir 中
LOGCAT:
E/tag: Failed to copy asset file: myfile.png
java.io.FileNotFoundException: myfile.png
at android.content.res.AssetManager.nativeOpenAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:833)
at android.content.res.AssetManager.open(AssetManager.java:810)
at org.pac.pac.act.copyAssets(act.java:97)
at org.pac.pac.act$2.run(act.java:78)
at java.lang.Thread.run(Thread.java:919)
2020-10-04 21:06:13.189 30767-30999/packagename E/tag: Failed to copy asset file: myfile2.png
java.io.FileNotFoundException: myfile2.png
at android.content.res.AssetManager.nativeOpenAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:833)
at android.content.res.AssetManager.open(AssetManager.java:810)
at org.pac.pac.act.copyAssets(act.java:97)
at org.pac.pac.act$2.run(act.java:78)
我添加了另一个名为 myfile2.png 的 PNG 并给出了同样的问题。
更新:
因此,我尝试在输入流中添加 myfile.png 而不是获取所有文件,但这也会返回相同的异常,即使该文件存在于 assets/sourcedir 文件夹中。
【问题讨论】:
-
我建议您编辑您的问题并为您的崩溃提供完整的堆栈跟踪。
-
补充说,我实际上已经用 try-catch 处理了这个异常,所以没有崩溃,但问题是一样的。
-
@CommonsWare 使用最新信息编辑了问题
-
我希望他们都失败。
filename是裸文件名。open()onAssetManager采用资产内的相对路径。您在open()呼叫中缺少"sourcedir"。
标签: java android android-assets