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 代码的更多相关文章

  1. java正则表达式移除网页中注释代码

    /** * 移除网页中注释掉的代码 * * @param str * @return */ public static String removedisablecode(String str) { P ...

  2. java简单统计.java文件中的有效代码行,空行,注释行

    package regxdemo; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundExc ...

  3. java编码规范_缩进和注释

    1.       缩进排版(Indentation) 4个空格常被作为缩进排版的一个单位.缩进的确切解释并未详细指定(空格 vs. 制表符).一个制表符等于n个空格(视具体的编辑器而定,Eclipse ...

  4. Java基础学习总结(92)——Java编码规范之排版、注释及命名

    为使开发人员养成良好的开发习惯,编写可读性强.易维护的程序,结合以往资料,现整理Java编码规范,将之作为开发人员的参照依据. 一.排版 1.相对独立的程序块之间必须加空行 下列情况应该使用一个空行: ...

  5. 007-使用python统计代码行数,空行以及注释

    # 自己写过的程序,统计一下你写过多少行代码.包括空行和注释,但是要分别列出来 1.打开文件方法 1.1 以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符 f ...

  6. linux过滤旧文件中的空行和注释行剩余内容组成新文件

    一.说明 在某些场景下我们想要将旧文件中空行和注释行过滤掉,将产生实际效果的行保留. 比如redis提供的配置示例文件中有很多用于说明的空行和注释行,我们想把产生实际效果的配置行筛选出来组成新的简洁的 ...

  7. java 生成jar包并保留注释

      java 生成jar包并保留注释 CreationTime--2018年7月17日08点32分 Author:Marydon 1.选中java项目-->右键-->Export: 2.去 ...

  8. python 判断是否是空行或注释行

    #coding:utf-8 '''''cdays-4-exercise-6.py 文件基本操作 @note: 文件读取写入, 列表排序, 字符串操作 @see: 字符串各方法可参考hekp(str)或 ...

  9. vim删除空行和注释

    vim删除空行和注释 来源:  http://jpuyy.com/2015/06/vim-delete-lines-using-regexp.html 删除空行 :g/^$/d 删除空行以及只有空格的 ...

随机推荐

  1. 页面中用Context.Handler传递

       最近被WCF弄得身心疲惫.今天抽空看了一下页面传值的一些技巧.传统的cookie session 什么的就不介绍了 今天介绍Context的用法 首先要应用using System.Runtim ...

  2. 如何用Eclipse将普通的JavaWeb项目转为Maven项目

    最新自己的第一个项目差不多稳定运行之后 想着将项目转为Maven项目.于是参考网上成功的将自己的普通的项目转为了maven项目,现在记录一下: 0.普通的java项目的结构如下: 1.接下来开始进行正 ...

  3. @Validated注解

    参考: https://blog.csdn.net/changerzhuo_319/article/details/55804651

  4. [bzoj1018][SHOI2008]堵塞的交通traffic_线段树

    bzoj-1018 SHOI-2008 堵塞的交通traffic 参考博客:https://www.cnblogs.com/MashiroSky/p/5973686.html 题目大意:有一天,由于某 ...

  5. 洛谷——P1057 传球游戏

    P1057 传球游戏 题目描述 上体育课的时候,小蛮的老师经常带着同学们一起做游戏.这次,老师带着同学们一起做传球游戏. 游戏规则是这样的:n个同学站成一个圆圈,其中的一个同学手里拿着一个球,当老师吹 ...

  6. spring boot 文件上传大小配置

    在启动类中,添加bean import javax.servlet.MultipartConfigElement; import org.springframework.boot.SpringAppl ...

  7. IO 函数

    http://www.cnblogs.com/orange1438/p/4613460.html

  8. UITableView性能的优化

    转载自http://hi.baidu.com/iosme/item/24e34c465b8b1636fb896075 1.使用不透明视图.
 不透明的视图可以极大地提高渲染的速度.因此如非必要,可以将 ...

  9. 数据库系统学习(九)-嵌入式SQL语言之基本技巧

    第九讲 嵌入式SQL语言之基本技巧 901 什么是嵌入式SQL语言 交互式SQL语言的局限性 嵌入式SQL语言 交互式和嵌入式语言的对比 高级语言中使用嵌入式语言需要解决的问题 902 程序与数据库连 ...

  10. Python基础语法06--文件

    Python 文件I/O 本章只讲述所有基本的的I/O函数,更多函数请参考Python标准文档. 打印到屏幕 最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式.此函数把你 ...