Android:更快的方式来读/写ZipInputStream?

时间:2011-07-27 22:38:26

标签: android fileoutputstream zipinputstream

我目前正在编写一个应用程序,它在我的assets文件夹中读取一个zip文件,其中包含一堆图像。我使用ZipInputStream API读取内容,然后将每个文件写入我的Environment.getExternalStorageDirectory()目录。我有一切正常,但第一次运行应用程序将图像写入存储目录是不可思议的慢。将我的图像写入光盘大约需要5分钟。我的代码如下所示:

ZipEntry ze = null;
ZipInputStream zin = new ZipInputStream(getAssets().open("myFile.zip"));
String location = getExternalStorageDirectory().getAbsolutePath() + "/test/images/";

    //Loop through the zip file
    while ((ze = zin.getNextEntry()) != null) {
         File f = new File(location + ze.getName());
          //Doesn't exist? Create to avoid FileNotFoundException
          if(f.exists()) {
             f.createNewFile();
          }
          FileOutputStream fout = new FileOutputStream(f);
          //Read contents and then write to file
          for (c = zin.read(); c != -1; c = zin.read()) {
             fout.write(c);
          }             
    }
    fout.close();
    zin.close();

读取特定条目的内容然后写入它的过程非常慢。我认为这更多的是阅读而不是写作。我已经读过你可以使用byte[]数组缓冲来加速这个过程,但这似乎不起作用!我尝试了这个,但它只读取了文件的一部分...

    FileOutputStream fout = new FileOutputStream(f);
    byte[] buffer = new byte[(int)ze.getSize()];
     //Read contents and then write to file
      for (c = zin.read(buffer); c != -1; c = zin.read(buffer)) {
            fout.write(c);
      }             
  }

当我这样做时,我只能写入大约600-800个字节。有没有办法加快这个?我是否错误地实现了缓冲区数组?

2 个答案:

答案 0 :(得分:11)

我找到了一个更好的解决方案来实现BuffererdOutputStream API。我的解决方案如下:

   byte[] buffer = new byte[2048];

   FileOutputStream fout = new FileOutputStream(f);
   BufferedOutputStream bos = new BufferedOutputStream(fout, buffer.length);

   int size;

    while ((size = zin.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, size);
        }
        //Close up shop..
        bos.flush();
        bos.close();

        fout.flush();
        fout.close();
        zin.closeEntry();

我设法将加载时间从平均约5分钟增加到约5分钟(取决于包中有多少图像)。希望这有帮助!

答案 1 :(得分:0)

尝试使用http://commons.apache.org/io/ 喜欢:

 InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
 try {
   System.out.println( IOUtils.toString( in ) );
 } finally {
   IOUtils.closeQuietly(in);
 }