竹山一叶

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  390 随笔 :: 0 文章 :: 0 评论 :: 192万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

最近做的一个Android项目中,需要将一个有20W份html文件的压缩包下载到本地,解压后在本地浏览;在解压的时候尝试了很多方法都无法完成解压(文件数量太大,要么解压超慢要么就内存溢出程序崩溃),后来放弃解压,直接从压缩包中读取文件,下面将方法整理如下


  • 通过ZipFile.getEntry(“文件名”)方法获取来获取压缩包中的指定文件对象

    public static void readZipFile(String file,String fileName) throws Exception {  
        ZipFile zf = new ZipFile(file);
        ZipEntry ze = zf.getEntry(fileName);
        InputStream in = zf.getInputStream(ze);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer result = new StringBuffer();
        while ((line = br.readLine()) != null) {  
            result.append(line+"\n");
        }
        System.out.println(result);
    }
    

    在上面的方法中,只要指定压缩包路径(file)以及压缩包中指定的文件名称(fileName),就可以读取到该html文件中的内容

  • 接下来我们对上面的方法进行改造,将指定文件从压缩包中读取出来并写入到指定的目录下,以便于在Android项目中进行查看

    /**
      * 
      * @param file 压缩包路径
      * @param saveRootDirectory 写入文件夹路径
      * @param fileName 文件名
      * @throws FileNotFoundException
      * @throws IOException
      */public static void writeZipFile(String file,String saveRootDirectory,String fileName) throws FileNotFoundException, IOException {
        int len = 0;
        ZipFile zf = new ZipFile(file);
        ZipEntry ze = zf.getEntry(fileName);
        InputStream read = zf.getInputStream(ze);
        File writeFile = new File(saveRootDirectory + fileName);
        if (!writeFile.exists()) {  
            File rootDirectoryFile = new File(saveRootDirectory);  
            //创建目录  if (!rootDirectoryFile.exists()) {  
                rootDirectoryFile.mkdirs();  
            } 
            //创建文件  
            writeFile.createNewFile();
    
            BufferedOutputStream write = new BufferedOutputStream(new FileOutputStream(file));
            //写入文件内容while ((len = read.read()) != -1) {
                write.write(len);
            }
            write.flush();  
            write.close();  
        }
        read.close();  
    }
    

    调用writeZipFile方法,将指定的文件(fileName)从压缩包(file)中读取出来后并写入到指定的文件夹(saveRootDirectory)下,通过WebView.loadUrl("file:///saveRootDirectory/fileName")实现html文件的查看,通过这种方式,我们避免了在移动端解压大文件时长时间的等待、甚至是导致程序崩溃这种不好的用户体验,需要查看某个文件从压缩包中读取即可。






posted on   竹山一叶  阅读(5814)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示