一般对于网页的优化 有JavaScript和css 图片等
现在要处理的是对html 进行压缩
Google上有个项目 [url=http://code.google.com/p/htmlcompressor/#Compressing_HTML]HtmlCompressor[/url] 还是不错的 可以直接看他的单元测试
jar 可以到源代码中找到 需要注意yuicompressor版本
现在只上个测试例子,做个记录
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
public class HtmlCompressorTest {
private static final String resPath = "d:/";
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testEnabled() throws Exception {
String source = readResource("testEnabled.htm");
HtmlCompressor compressor = new HtmlCompressor();
compressor.setRemoveComments(true);
compressor.setRemoveIntertagSpaces(true);
compressor.setRemoveQuotes(true);
compressor.setRemoveMultiSpaces(true);
compressor.setCompressJavaScript(true);
compressor.setCompressCss(true);
writeResource("testEnabledResult.html",compressor.compress(source));
}
private String readResource(String filename) {
StringBuilder builder = new StringBuilder();
try {
FileInputStream stream = new FileInputStream(new File(resPath + filename));
try {
Reader reader = new BufferedReader(new InputStreamReader(stream));
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
} finally {
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
private void writeResource(String filename, String content) {
try {
Writer output = new BufferedWriter(new FileWriter(new File(resPath + filename)));
try {
output.write(content);
} finally {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}