Let's explain it first
I'm using a webView to load a HTML app. To protect the source a bit (script-kiddie protection) I want to load the html code from a (protected) zip file. The html code is already packed, minified, combined etc so is only 700kb in size (unpacked). This works pretty well but there is one problem, it is a bit slow.
In the example below I read the html file from the zip and put the result in a string. This string will be used to load the html code into the webview
by using the following code:
this.webView.loadDataWithBaseURL("file:///android_asset/", this.unzipStream(sFileName), "text/html", "UTF-8", "");
I have played with different solutions to get it faster and figure out that the bottleneck is at reading the contents from the zip. I increased the read buffer's blocksize but doesn't help, it never reads the full blocksize. For example, when I used 4096 bytes (4kb) as blocksize it reads only 700 to 1100 bytes at once.
Question(s):
- How can I force the read function to use the full blocksize specified?
- Otherwise, is there another better way to do it (for example put it directly into webview)?
Here is the code I have made:
public String unzipStream( String sFileName )
{
final int BLOCKSIZE = 4096;
//String sResult = "";
long iSize = 0;
int iReaded = 0;
ByteArrayOutputStream sb = new ByteArrayOutputStream();
try {
InputStream is = this.activity.getAssets().open( sFileName );
BufferedInputStream fin = new BufferedInputStream( is );
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze;
while( (iSize == 0) && ((ze = zin.getNextEntry()) != null) && !ze.isDirectory() )
{
byte data[] = new byte[BLOCKSIZE];
long iTotal = ze.getSize();
while ((iReaded = zin.read(data,0,BLOCKSIZE)) > 0 && ((iSize+=iReaded) <= iTotal) )
{
sb.write(data,0,iReaded);
}
zin.closeEntry();
}
zin.close();
}
catch(Exception e)
{
System.out.println("Error unzip: "+e.getMessage());
//sResult = "";
iSize = 0;
}
if( iSize > 0 )
{
//Base64.
try {
return sb.toString("UTF-8");
//sResult = new String( Base64.decode(sb.toString("UTF-8"), Base64.DEFAULT), Charset.forName("UTF-8") );
}
catch(Exception ee)
{
//sResult = "";
}
}
return "";
}
Maybe another way to do it:
Also found this java zipfile class http://www.lingala.net/zip4j/. It makes it easier to handle (password protected) zip files but does not include a function (at least I think so) to unzip it to string. Found nothing when searching on it. Is this possible anyway with this class?