Xamarin Android:无需AssetManager获取Assets文件路径适配FunnyCode
Android平台下Assets文件路径获取及替代方案
Android平台上,Assets文件夹内的文件是打包在APK压缩包中的资源,没有真实的文件系统路径,无法直接通过路径字符串访问。下面分两种场景给出解决方案:
一、必须传入文件路径的处理方式
如果FunnyCode只能接受文件路径参数,唯一可行的办法是把Assets里的文件复制到应用可读写的目录(比如私有文件目录或缓存目录),然后使用复制后的文件路径。
原生Android示例代码
// 复制Assets文件到私有目录 private String copyAssetToFilesDir(Context context, String assetFileName) { File outputFile = new File(context.getFilesDir(), assetFileName); if (outputFile.exists()) { return outputFile.getAbsolutePath(); // 文件已存在,直接返回路径 } try (InputStream in = context.getAssets().open(assetFileName); OutputStream out = new FileOutputStream(outputFile)) { byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } return outputFile.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); return null; } } // 调用方式 String filePath = copyAssetToFilesDir(this, "your_file_name"); if (filePath != null) { FunnyCode(filePath); }
Unity开发场景示例代码
IEnumerator CopyAssetToPersistentPath(string assetFileName) { string persistentPath = Path.Combine(Application.persistentDataPath, assetFileName); if (File.Exists(persistentPath)) { FunnyCode(persistentPath); yield break; } string streamingPath = Path.Combine(Application.streamingAssetsPath, assetFileName); using (UnityWebRequest request = UnityWebRequest.Get(streamingPath)) { yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) { File.WriteAllBytes(persistentPath, request.downloadHandler.data); FunnyCode(persistentPath); } else { Debug.LogError("复制文件失败: " + request.error); } } }
二、更优的替代方案
如果可以修改FunnyCode的实现,建议直接将其参数改为接受输入流或字节流,无需复制文件,直接读取Assets资源即可:
原生Android修改示例
// 修改后的方法 void FunnyCode(InputStream inputStream) { // 原逻辑改为从inputStream读取数据 } // 调用方式 try (InputStream in = getAssets().open("your_file_name")) { FunnyCode(in); } catch (IOException e) { e.printStackTrace(); }
Unity修改示例
// 修改后的方法 void FunnyCode(Stream stream) { // 原逻辑改为从stream读取数据 } // 调用方式 string streamingPath = Path.Combine(Application.streamingAssetsPath, "your_file_name"); using (UnityWebRequest request = UnityWebRequest.Get(streamingPath)) { yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) { using (MemoryStream stream = new MemoryStream(request.downloadHandler.data)) { FunnyCode(stream); } } }
另外,若选择将文件移到外部存储,需注意Android 10及以上的分区存储规则,需申请对应存储权限,但这种方式存在文件被删除、权限失效的风险,安全性不如应用私有目录,不推荐。
内容的提问来源于stack exchange,提问作者pqzpkaot
相关产品推荐
相关产品推荐

