【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 删除空行以及只有空格的 ...
随机推荐
- 在线预览Word,Excel
今天在项目中遇到了在线预览word的需求,经过查阅资料与测试发现可以解决问题,特做记录: 方式: http://view.officeapps.live.com/op/view.aspx?src= s ...
- bigdata related
hive: http://lxw1234.com/archives/2015/07/413.htm 搜狗实验室数据集: https://www.sogou.com/labs/resource/list ...
- PatentTips - Blending a Graphic over a Video
Television broadcasts of events can be enhanced by providing graphics that are blended with other im ...
- Redis对象的设计与实现
一.Redis对象结构Redis中的每个对象都由一个redisObject结构表示: typedef struct redisObject { unsigned type;//类型 unsigned ...
- CODEVS_2800 送外卖 状态压缩+动态规划
原题链接:http://codevs.cn/problem/2800/ 题目描述 Description 有一个送外卖的,他手上有n份订单,他要把n份东西,分别送达n个不同的客户的手上.n个不同的客户 ...
- CodeChef - LEMOVIE Little Elephant and Movies
Read problems statements in Mandarin Chineseand Russian. Little Elephant from Zoo of Lviv likes to w ...
- ImportError: No module named _curses;Color support is disabled, python-curses is not installed.解决办法
linux系统默认安装了python2.6, 但是发现python2.7 import curses时 提示 找不到_curses 错误. 用pip(python2.7 )安装了curses-204 ...
- Android Camera 拍照 三星BUG总结
Android Camera 三星BUG : 近期在Android项目中使用拍照功能 , 其他型号的手机执行成功了 只有在三星的相机上遇到了bug . BUG详细体现为 : (1) 摄像头拍照后图 ...
- iOS开发之UITabBarController和UICollectionView的使用
这一篇要记录的是iOS开发中UITabBarController控件和UICollectionView控件的使用.APP跑起来之后的效果例如以下图: watermark/2/text/aHR0cDov ...
- 线段树区间更新,区间统计+离散化 POJ 2528 Mayor's posters
题意:有一个非常长的板子(10000000长),在上面贴n(n<=10000)张海报.问最后从外面能看到几张不同的海报. 由于板子有10000000长,直接建树肯定会爆,所以须要离散化处理,对于 ...