JAVA使用YUI压缩CSS/JS

前言

    JS/CSS文件压缩我们经常会用到,可以在网上找在线压缩或者本地直接使用,我这里使用的是yahoo开源组件YUI Compressor。
首先介绍一下YUI Compressor,它是一个用来压缩JS和CSS文件的工具,采用Java开发。JavaScript和CSS缩小的目标是始终保持代码的操作质量,同时减少其整体字节占用,YUI Compressor设计为100%安全的JavaScript分选程序,并且比大多数其他工具具有更高的压缩比。与JSMin相比,YUI Library 的测试节省了20%以上(HTTP压缩后为10%)。YUI Compressor还可以通过使用Isaac Schlueter的基于正则表达式的CSS minifier 的端口来压缩CSS文件。,下面为大家分享一下使用yuicompressor压缩js文件和压缩css文件。
    压缩文件可以减小文件大小,JS文件会默认去掉分号,注释,会将一些参数名改为a,b,c等,减低可读性。

YUI Compressor官网:http://yui.github.io/yuicompressor/

jar包下载:链接:https://pan.baidu.com/s/1cKM5pxgMduxBIdJRGXX9vg 提取码:q2s2 

开始使用

    js代码:

/**
 * 验证密码和账户
 */
function validate2(username, password) {
    if (username != "zhangsan") {
        alert("userName is error:" + c)
    }
    if (password != "123456") {
        alert("password is error:" + d)
    }
};

 

    进行压缩:

D:>java -jar yuicompressor-2.4.7.jar index.js -v -o index-min.js --charset UTF-8

   参数说明:

index.js  需要压缩的源文件
-v -o 显示信息与指定输出文件名字
index-min.js 压缩后的文件
--charset 指定编码格式

     压缩后文件:

function validate2(b,a){if(b!="zhangsan"){alert("userName is error:"+c)}if(a!="123456"){alert("password is error:"+d)}};

压缩后文件改变了参数名,去掉了分号。

    不去分号:

D:>java -jar yuicompressor-2.4.7.jar index.js -v --preserve-semi -o index-min.js --charset UTF-8

    压缩css:

D:>java -jar yuicompressor-2.4.7.jar index.css -v -o index1-min.css --charset UTF-8

JAVA代码

    实现原理 通过java执行cmd命令,for循环遍历文件夹下js/css文件。可实现批量压缩

  1 import java.io.File;
  2 import java.io.IOException;
  3 import java.util.ArrayList;
  4 import java.util.Arrays;
  5 import java.util.Date;
  6 import java.util.List;
  7 
  8 /**
  9  * 通过yuicompressor压缩JS|CSS文件工具类
 10  * @author Administrator
 11  *
 12  */
 13 public class CompressUtils {
 14     private static final String encoding = "utf-8";
 15     private static final String[] suffixArray = { ".js", ".css" };
 16 
 17     public static void main(String[] args) {
 18         String yuiPath = "D:/yuicompressor-2.4.7.jar";
 19         String filePath = "D:/js";
 20 
 21         compressFile(yuiPath, filePath);
 22     }
 23 
 24     /**
 25      * 压缩指定文件夹下所有的js/css
 26      * 
 27      * @param yuiPath
 28      *            yuicompressor-2.4.7.jar文件路径
 29      * @param filePath
 30      *            要压缩的文件夹路径
 31      */
 32     public static void compressFile(String yuiPath, String filePath) {
 33         File file = new File(filePath);
 34         List<String> commondList = new ArrayList<String>();
 35         initCommondList(yuiPath, commondList, file);
 36         excuteCompress(commondList);
 37     }
 38 
 39     /**
 40      * 执行压缩命令
 41      * @param commondList
 42      */
 43     private static void excuteCompress(List<String> commondList) {
 44         Runtime runTime = Runtime.getRuntime();
 45         Date startTime = new Date();
 46         Long count = 0L;
 47         for (String cmd : commondList) {
 48             try {
 49                 System.out.println(cmd);
 50                 runTime.exec(cmd);
 51                 count++;
 52             } catch (IOException e) {
 53                 e.printStackTrace();
 54             }
 55         }
 56         Date endTime = new Date();
 57         Long cost = endTime.getTime() - startTime.getTime();
 58         System.out.println("压缩完成,耗时:" + cost + "ms,共压缩文件个数:" + count);
 59     }
 60 
 61     /**
 62      * 初始化压缩命令
 63      * @param yuiPath
 64      * @param commondList
 65      * @param file
 66      */
 67     private static void initCommondList(String yuiPath,
 68             List<String> commondList, File file) {
 69         if (file.isDirectory()) {
 70             File[] files = file.listFiles();
 71             // 如果某个文件夹是空文件夹,则跳过
 72             if (files == null) {
 73                 return;
 74             }
 75             for (File f : files) {
 76                 initCommondList(yuiPath, commondList, f);
 77             }
 78         } else {
 79             String fileName = file.getName();
 80             String suffix = fileName.substring(fileName.lastIndexOf("."),
 81                     fileName.length());
 82 
 83             List<String> suffixList = Arrays.asList(suffixArray);
 84             if (suffixList.contains(suffix)
 85                     && !fileName.endsWith("-min" + suffix)) {
 86                 StringBuffer sb = new StringBuffer();
 87                 sb.append("java -jar ");
 88                 sb.append(yuiPath);
 89                 sb.append(" --type ");
 90                 sb.append(suffix.substring(suffix.indexOf(".") + 1));
 91                 sb.append(" --charset ");
 92                 sb.append(encoding).append(" ");
 93                 sb.append(file.getPath()).append(" ");
 94                 sb.append("-o").append(" ");
 95                 sb.append(file.getPath().replace(suffix, "-min" + suffix));
 96 
 97                 commondList.add(sb.toString());
 98             }
 99 
100         }
101     }
102 }

 

 

    YUI参数使用帮助:

java -jar yuicompressor-x.y.z.jar
Usage: java -jar yuicompressor-x.y.z.jar [options] [input file]

  Global Options
    -h, --help                Displays this information
    --type <js|css>           Specifies the type of the input file
    --charset <charset>       Read the input file using <charset>
    --line-break <column>     Insert a line break after the specified column number
    -v, --verbose             Display informational messages and warnings
    -o <file>                 Place the output into <file> or a file pattern.
                              Defaults to stdout.

  JavaScript Options
    --nomunge                 Minify only, do not obfuscate
    --preserve-semi           Preserve all semicolons
    --disable-optimizations   Disable all micro optimizations

GLOBAL OPTIONS

  -h, --help
      Prints help on how to use the YUI Compressor

  --line-break
      Some source control tools don’t like files containing lines longer than,
      say 8000 characters. The linebreak option is used in that case to split
      long lines after a specific column. It can also be used to make the code
      more readable, easier to debug (especially with the MS Script Debugger)
      Specify 0 to get a line break after each semi-colon in JavaScript, and
      after each rule in CSS.

  --type js|css
      The type of compressor (JavaScript or CSS) is chosen based on the
      extension of the input file name (.js or .css) This option is required
      if no input file has been specified. Otherwise, this option is only
      required if the input file extension is neither ’js’ nor ’css’.

  --charset character-set
      If a supported character set is specified, the YUI Compressor will use it
      to read the input file. Otherwise, it will assume that the platform’s
      default character set is being used. The output file is encoded using
      the same character set.

  -o outfile

      Place output in file outfile. If not specified, the YUI Compressor will
      default to the standard output, which you can redirect to a file.
      Supports a filter syntax for expressing the output pattern when there are
      multiple input files.  ex:
          java -jar yuicompressor.jar -o ’.css$:-min.css’ *.css
      ... will minify all .css files and save them as -min.css

  -v, --verbose
      Display informational messages and warnings.

JAVASCRIPT ONLY OPTIONS

  --nomunge
      Minify only. Do not obfuscate local symbols.

  --preserve-semi
      Preserve unnecessary semicolons (such as right before a ’}’) This option
      is useful when compressed code has to be run through JSLint (which is the
      case of YUI for example)

  --disable-optimizations
      Disable all the built-in micro optimizations.

 

 
posted @ 2018-12-14 16:06  粉红顽皮蛇  阅读(1759)  评论(0编辑  收藏  举报