【Java】通过移除空行和注释来压缩 JavaScript 代码
1. [代码]JavaScriptCompressor.java
/**
* This file is part of the Echo Web Application Framework (hereinafter "Echo").
* Copyright (C) 2002-2009 NextApp, Inc.
*
* Compresses a String containing JavaScript by removing comments and whitespace.
*/
public class JavaScriptCompressor {
private static final char LINE_FEED = '\n';
private static final char CARRIAGE_RETURN = '\r';
private static final char SPACE = ' ';
private static final char TAB = '\t';
/**
* Compresses a String containing JavaScript by removing comments and
* whitespace.
*
* @param script the String to compress
* @return a compressed version
*/
public static String compress(String script) {
JavaScriptCompressor jsc = new JavaScriptCompressor(script);
return jsc.outputBuffer.toString();
}
/** Original JavaScript text. */
private String script;
/**
* Compressed output buffer.
* This buffer may only be modified by invoking the <code>append()</code>
* method.
*/
private StringBuffer outputBuffer;
/** Current parser cursor position in original text. */
private int pos;
/** Character at parser cursor position. */
private char ch;
/** Last character appended to buffer. */
private char lastAppend;
/** Flag indicating if end-of-buffer has been reached. */
private boolean endReached;
/** Flag indicating whether content has been appended after last identifier. */
private boolean contentAppendedAfterLastIdentifier = true;
/**
* Creates a new <code>JavaScriptCompressor</code> instance.
*
* @param script
*/
private JavaScriptCompressor(String script) {
this.script = script;
outputBuffer = new StringBuffer(script.length());
nextChar();
while (!endReached) {
if (Character.isJavaIdentifierStart(ch)) {
renderIdentifier();
} else if (ch == ' ') {
skipWhiteSpace();
} else if (isWhitespace()) {
// Compress whitespace
skipWhiteSpace();
} else if ((ch == '"') || (ch == '\'')) {
// Handle strings
renderString();
} else if (ch == '/') {
// Handle comments
nextChar();
if (ch == '/') {
nextChar();
skipLineComment();
} else if (ch == '*') {
nextChar();
skipBlockComment();
} else {
append('/');
}
} else {
append(ch);
nextChar();
}
}
}
/**
* Append character to output.
* flash动画
* @param ch the character to append
*/http://www.huiyi8.com/donghua/
private void append(char ch) {
lastAppend = ch;
outputBuffer.append(ch);
contentAppendedAfterLastIdentifier = true;
}
/**
* Determines if current character is whitespace.
*
* @return true if the character is whitespace
*/
private boolean isWhitespace() {
return ch == CARRIAGE_RETURN || ch == SPACE || ch == TAB || ch == LINE_FEED;
}
/**
* Load next character.
*/
private void nextChar() {
if (!endReached) {
if (pos < script.length()) {
ch = script.charAt(pos++);
} else {
endReached = true;
ch = 0;
}
}
}
/**
* Adds an identifier to output.
*/
private void renderIdentifier() {
if (!contentAppendedAfterLastIdentifier)
append(SPACE);
append(ch);
nextChar();
while (Character.isJavaIdentifierPart(ch)) {
append(ch);
nextChar();
}
contentAppendedAfterLastIdentifier = false;
}
/**
* Adds quoted String starting at current character to output.
*/
private void renderString() {
char startCh = ch; // Save quote char
append(ch);
nextChar();
while (true) {
if ((ch == LINE_FEED) || (ch == CARRIAGE_RETURN) || (endReached)) {
// JavaScript error: string not terminated
return;
} else {
if (ch == '\\') {
append(ch);
nextChar();
if ((ch == LINE_FEED) || (ch == CARRIAGE_RETURN) || (endReached)) {
// JavaScript error: string not terminated
return;
}
append(ch);
nextChar();
} else {
append(ch);
if (ch == startCh) {
nextChar();
return;
}
nextChar();
}
}
}
}
/**
* Moves cursor past a line comment.
*/
private void skipLineComment() {
while ((ch != CARRIAGE_RETURN) && (ch != LINE_FEED)) {
if (endReached) {
return;
}
nextChar();
}
}
/**
* Moves cursor past a block comment.
*/
private void skipBlockComment() {
while (true) {
if (endReached) {
return;
}
if (ch == '*') {
nextChar();
if (ch == '/') {
nextChar();
return;
}
} else
nextChar();
}
}
/**
* Renders a new line character, provided previously rendered character
* is not a newline.
*/
private void renderNewLine() {
if (lastAppend != '\n' && lastAppend != '\r') {
append('\n');
}
}
/**
* Moves cursor past white space (including newlines).
*/
private void skipWhiteSpace() {
if (ch == LINE_FEED || ch == CARRIAGE_RETURN) {
renderNewLine();
} else {
append(ch);
}
nextChar();
while (ch == LINE_FEED || ch == CARRIAGE_RETURN || ch == SPACE || ch == TAB) {
if (ch == LINE_FEED || ch == CARRIAGE_RETURN) {
renderNewLine();
}
nextChar();
}
}
}
【Java】通过移除空行和注释来压缩 JavaScript 代码的更多相关文章
- java正则表达式移除网页中注释代码
/** * 移除网页中注释掉的代码 * * @param str * @return */ public static String removedisablecode(String str) { P ...
- java简单统计.java文件中的有效代码行,空行,注释行
package regxdemo; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundExc ...
- java编码规范_缩进和注释
1. 缩进排版(Indentation) 4个空格常被作为缩进排版的一个单位.缩进的确切解释并未详细指定(空格 vs. 制表符).一个制表符等于n个空格(视具体的编辑器而定,Eclipse ...
- Java基础学习总结(92)——Java编码规范之排版、注释及命名
为使开发人员养成良好的开发习惯,编写可读性强.易维护的程序,结合以往资料,现整理Java编码规范,将之作为开发人员的参照依据. 一.排版 1.相对独立的程序块之间必须加空行 下列情况应该使用一个空行: ...
- 007-使用python统计代码行数,空行以及注释
# 自己写过的程序,统计一下你写过多少行代码.包括空行和注释,但是要分别列出来 1.打开文件方法 1.1 以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符 f ...
- linux过滤旧文件中的空行和注释行剩余内容组成新文件
一.说明 在某些场景下我们想要将旧文件中空行和注释行过滤掉,将产生实际效果的行保留. 比如redis提供的配置示例文件中有很多用于说明的空行和注释行,我们想把产生实际效果的配置行筛选出来组成新的简洁的 ...
- java 生成jar包并保留注释
java 生成jar包并保留注释 CreationTime--2018年7月17日08点32分 Author:Marydon 1.选中java项目-->右键-->Export: 2.去 ...
- python 判断是否是空行或注释行
#coding:utf-8 '''''cdays-4-exercise-6.py 文件基本操作 @note: 文件读取写入, 列表排序, 字符串操作 @see: 字符串各方法可参考hekp(str)或 ...
- vim删除空行和注释
vim删除空行和注释 来源: http://jpuyy.com/2015/06/vim-delete-lines-using-regexp.html 删除空行 :g/^$/d 删除空行以及只有空格的 ...
随机推荐
- 洛谷 [P2594] 染色游戏
博弈论+SG函数的应用 这是一个二维翻硬币问题 一维翻硬币问题有一个结论: 局面的SG值等于局面中所有反面朝上的硬币单独存在时的SG值的异或和 这个结论同样适用于二维的翻硬币问题 证明可以用数学归纳法 ...
- msp430入门学习44
msp430的其他十二 msp430入门学习
- 每日记录 2016-4-29 HTML5本地存储
HTML5本地存储 一.HTML5 localStorage 在HTML5中,本地存储是一个window的属性,包括localStorage和 sessionStorage,从名字应该可以很清楚的辨认 ...
- ubuntu下安装翻译软件
原文: http://sixipiaoyang.blog.163.com/blog/static/6232358820144146386437/ Ubuntu下常用的翻译软件有StarDict,Gol ...
- raspi集成库及安装
原文:http://blog.csdn.net/xukai871105/article/details/12684617 树莓派来自国外,国外嵌入式开源领域具有良好的分享精神,树莓派各种集成库也层 ...
- 转 vs2010转vs2008 其他的一样
如果你使用VS2010的任何版本写代码,那么在VS2008中就不能打开VS2010的解决方案了,为此,通过以下三步就可以解决了一.对于工程名.sln; 1.用你喜欢的编辑器打开sln文件,比如note ...
- XStream 数组(List)输出结构
<!-- 期望的DOM树 --> <Articles> <item> <Title>微信SDK初步结构</Title> <Descri ...
- 第04章-VTK基础(3)
[译者:这个系列教程是以Kitware公司出版的<VTK User's Guide -11th edition>一书作的中文翻译(出版时间2010年,ISBN: 978-1-930934- ...
- 小博客| 登录 | 注册 | 留言 | 提Bug 小博客
浏览(1502) 赞(29) 一直以来都想开发一个自己的网站,总想做一个网站然后让千千万万的人去访问,去使用,然后收到热烈的好评, 再然后某某著名机构有意投资我的网站(其实收购也是没有问题的), ...
- ActiveMQ(五) 转
package pfs.y2017.m11.mq.activemq.demo05; import javax.jms.Connection; import javax.jms.ConnectionFa ...