js、css、jsp文件压缩

来源:互联网 发布:循环更新数据库 编辑:程序博客网 时间:2024/06/05 23:22
package com.fort;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


/**
 * 压缩js、css、jsp文件
 * @version 1.0
 * @create at 2017-04-05
 */
public class CompressJsp {
public static int num = 0;

public static void main(String[] args) throws IOException{
LoopCompress("D:\\Program Files (x86)\\server\\apache-tomcat-7.0.55x86\\webapps\\fort");
System.out.print(num);
}


/**
* 循环遍历压缩文件 

* @param filePath 文件/文件夹路径
* @return boolean压缩结果
*/
public static void LoopCompress(String filePath){
File file = new File(filePath);

if (file.isFile()){
CompressFile(file.getPath());
} else {
File[] listFile = file.listFiles(); 
if (listFile != null && listFile.length > 0){
for (File tempFile : listFile){
if (tempFile.isFile()){
CompressFile(tempFile.getPath());
} else {
LoopCompress(tempFile.getPath());
}
}
}
}


/**
* 将文件内容进行压缩 

* @param filePath要压缩的文件
* @return boolean 压缩结果
*/
public static boolean  CompressFile(String filePath){
boolean flag = false;
BufferedReader bf = null;
BufferedWriter bufferWritter = null;
String encoding = "UTF-8";

try {
File file = new File(filePath);
if (file.exists()){
String fileType = file.getName().substring(file.getName().lastIndexOf(".") + 1);
if (/*"js".equals(fileType) || "css".equals(fileType) ||*/ "jsp".equals(fileType)){
bf = new BufferedReader(new InputStreamReader(  
               new FileInputStream(file), encoding));
String str = null;
String result = "";
while((str = bf.readLine()) != null){
str = str.trim();
// 如果当前行为空
if ("".equals(str)){
continue;
}
// 以注释//开头则直接跳过
if ("".equals(str) || str.startsWith("//")){
System.out.println(str);
continue;

// 包含<!-- --> 注释的去除
if (str.startsWith("<!--") && str.endsWith("-->")){
System.out.println(str);
continue;
}
// 包含/**/的去除
if (str.startsWith("/*") && str.endsWith("*/")){
System.out.println(str);
continue;
}


// 如果已< 开头以> 结尾、以分号结尾、以}结尾则不换行
/*if (((str.startsWith("<") && str.endsWith(">"))
|| str.endsWith(";") 
|| str.endsWith("}")
|| str.endsWith("+")
|| str.endsWith("{")
|| str.endsWith(",")) && (!str.contains("//"))){
str = str + " ";

} else {
str = str + "\r\n";
}*/

result +=  str + "\r\n";
}
bf.close();

// 将压缩好的内容重新写入文件
       bufferWritter = new BufferedWriter(new OutputStreamWriter(  
               new FileOutputStream(file), encoding));
       bufferWritter.write(result);
       bufferWritter.close();
       flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bf != null){
bf.close();
}
if (bufferWritter != null) {
bufferWritter.close();
}
} catch (IOException e) {
e.printStackTrace();
}

}
return flag;
}
}