开发者

How to get the compression ratio for a GZipped file?

Here is how I compressed the data:

<%@ page import="javax.servlet.jsp.*,java.io.*,java开发者_如何转开发.util.zip.*" %>

<%
String encodings = request.getHeader("Accept-Encoding");
PrintWriter outWriter = null;

if ((encodings != null) && (encodings.indexOf("gzip") != -1)) {
  OutputStream outA = response.getOutputStream();
  outWriter = new PrintWriter(new GZIPOutputStream(outA), false);
  response.setHeader("Content-Encoding", "gzip");
  int a = response.getBufferSize();
  System.out.println("ZIPPED VERSION BF:"+a);
} 
else {
  System.out.println("UN-ZIPPED VERSION");
  outWriter = new PrintWriter(response.getOutputStream(), false);
}

outWriter.println("<HTML><BODY>");

for(int i=0; i<1000; i++) {
  outWriter.println(" blah blah blah<br>");
}

outWriter.println("</BODY></HTML>");
outWriter.close();
%>


Sorry to sound harsh, but this approach is totally wrong. First, you don't want to do this in a JSP file due to at least two reasons: 1) raw Java code (scriptlets) belongs in real Java classes and 2) JSP is for character data, not for binary data, it would only corrupt the data. Second, any decent appserver provides a configuration option whether to automatically GZIP the response or not. In for example Tomcat 6.0, you can just extend the <Connector> element in /conf/server.xml with a compression attribute which is set to "on":

<Connector ... compression="on" />

Also see this article for more hints with regard to webapp performance.

Back to your actual question: there's no setting to alter the compression ratio for GZIP. It's also not needed.

Update: I realized that you asked get, not set. Well, use a HTTP client and calculate the length of the InputStream. Here's a basic kickoff example with help of java.net.URLConnection:

URLConnection connection = new URL("http://localhost/context/page.jsp");
connection.setRequestProperty("Accept-Encoding", "gzip"); // Outcomment this to turn off GZIP.
InputStream input = connection.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
for (int data = 0; (data = input.read()) != -1; output.write(data));
System.out.println("Length: " + output.toByteArray().length + " bytes");

Then just do the primary school math to get the compression ratio. Divide, multiply, etc ;)


Unless I am missing something here you just manually calculate original size divided by compressed size.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜