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

Jac*_*ack 4 android zipinputstream fileoutputstream

我目前正在编写一个应用程序,它在我的资源文件夹中读取一个zip文件,其中包含一堆图像.我正在使用ZipInputStreamAPI来读取内容,然后将每个文件写入my: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();
Run Code Online (Sandbox Code Playgroud)

读取特定条目的内容然后写入它的过程非常慢.我认为这更多的是阅读而不是写作.我已经读过你可以使用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);
      }             
  }
Run Code Online (Sandbox Code Playgroud)

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

Jac*_*ack 12

我找到了一个更好的解决方案来实现BuffererdOutputStreamAPI.我的解决方案如下所示:

   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();
Run Code Online (Sandbox Code Playgroud)

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


小智 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);
 }
Run Code Online (Sandbox Code Playgroud)