【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 删除空行以及只有空格的 ...
随机推荐
- StoryBoard中,TableView位置总是在顶部出现空白的解决
重设TableView的 contentInset 属性可解决. _tableView.contentInset = UIEdgeInsetsMake( -30, 0, 0, 0);
- Yii 之控制器创建使用
在根目录下的controllers目录下创建控制器HelloController.php: <?php namespace app\controllers; use yii\web\Contro ...
- delphi 与 sqlite3
delphi与sqlite file:0 前言 本文的目的在于采用流水账方式来记录学习delphi访问嵌入式数据库sqlite中的一些点滴.欢迎各位同好共同学习和批评指正. file:1 准备工作 ...
- 【Java TCP/IP Socket】深入剖析socket——数据传输的底层实现
底层数据结构 如果不理解套接字的具体实现所关联的数据结构和底层协议的工作细节,就很难抓住网络编程的精妙之处,对于TCP套接字来说,更是如此.套接字所关联的底层的数据结构集包含了特定Socket实例所关 ...
- inux IO 内核参数调优 之 参数调节和场景分析
http://backend.blog.163.com/blog/static/2022941262013112081215609/ http://blog.csdn.net/icycode/arti ...
- 配置maven从私服上下载构件
maven 本地setting.xml配置 <!--配置maven从私服上下载构件 --> <profiles> <profile> <repositorie ...
- Windows下Python安装pyecharts
都说pyechart用来可视化好,可是安装的时候各种坑 正常情况是 pip install pyecharts 然后各种报错,找到一种可行的方式 在https://pypi.org/project/p ...
- 【Todo】ssh的原理和实践
有空的时候补充,可以参考 http://www.ruanyifeng.com/blog/2011/12/ssh_remote_login.html http://www.ruanyifeng.com/ ...
- win7下 安装 source code pro
转: http://my.oschina.net/yearnfar/blog/325107 source code pro 字体安装, 一. 去 https://github.com/adobe-fo ...
- 转:一个android开发者独立开发社交app全过程
http://www.cnblogs.com/linguanh/p/5683069.html