如何用Java读取Cordova资源文件index.html?路径错误求助
在Cordova Android中读取assets目录下的index.html文件
你当前的代码无法读取目标文件,核心原因是file:///android_asset/www/index.html是Android资产文件的URL标识,并非设备本地文件系统的真实路径,Paths.get()和Files.readAllLines()只能访问普通文件系统的文件,无法直接读取APK打包的assets资源。
正确的做法是使用Android提供的AssetManager来访问assets目录下的文件,以下是可行的代码示例:
// 假设你在Cordova插件类中,通过cordova实例获取Activity的AssetManager AssetManager assetManager = cordova.getActivity().getAssets(); Charset charset = StandardCharsets.UTF_8; // 使用try-with-resources自动关闭流资源 try (InputStream inputStream = assetManager.open("www/index.html"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException ex) { System.out.format("I/O error: %s%n", ex); }
几点关键说明:
assetManager.open()的参数是相对于assets目录的相对路径,直接写www/index.html即可,不需要添加任何前缀。- 如果你是在普通Android组件(比如Activity)中,直接调用
getAssets()就能获取AssetManager实例。 - try-with-resources语法会自动关闭
InputStream和BufferedReader,避免资源泄漏问题。
内容的提问来源于stack exchange,提问作者user6057915
相关产品推荐
相关产品推荐

