android怎么样读取META-INF目录下的某文件

Android 码拜 8年前 (2016-03-28) 2896次浏览
如题,本人在META-INF目录里放了一个txt文本,android有什么方法能读取到这个txt文本吗?有没有相关方法或博客链接参考一下
解决方案

10

读不到吧,一般放到asserts目录下面

30

大致思路是将Apk文件当作一个zip文件,获取apk文件路径之后,利用ZipFile, ZipEntry, ZipInputstream等zip操作接口访问就可以了。
大致代码如下(随手写的,没有经过调试):

private void getFileContent(Context context) {
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                
                if (entryName.startsWith("META-INF/xxx")) { //xxx 表示要读取的文件名
                    //利用ZipInputStream读取文件
                   long size = entry.getSize();  
                   if (size > 0) {  
                       BufferedReader br = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));  
                       String line;  
                       while ((line = br.readLine()) != null) {  //文件内容都在这里输出了,根据你的需要做改变
                           System.out.println(line);  
                       }  
                       br.close();  
                   }
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明android怎么样读取META-INF目录下的某文件
喜欢 (0)
[1034331897@qq.com]
分享 (0)