jeffen

最近做的一个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文件的查看,通过这种方式,我们避免了在移动端解压大文件时长时间的等待、甚至是导致程序崩溃这种不好的用户体验,需要查看某个文件从压缩包中读取即可。






分类:

技术点:

相关文章:

  • 2021-04-11
  • 2021-09-10
  • 2021-10-08
  • 2022-12-23
  • 2021-12-17
  • 2021-09-20
  • 2021-10-24
  • 2022-12-23
猜你喜欢
  • 2021-09-11
  • 2020-07-28
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2021-08-25
  • 2022-12-23
相关资源
相似解决方案