想法:参数:目录路径,
目录路径下新建压缩后文件存放目录,
查找下面文件列表,若是.css文件就进行压缩,然后生成到新建压缩后文件存放的目录.
话不多说,直接上代码:
生成新目录,获取文件列表
public static void compressDirCss(String dirPath){
Date startTime = new Date();
Long count = 0L;
File file = new File(dirPath);
if(file.isDirectory()){
File[] files = file.listFiles();
// 如果某个文件夹是空文件夹,则跳过
if (files == null&&files.length>0) {
return;
}
File ysNewF = new File(dirPath+separatorC+ysNew);
if(ysNewF.exists()&&ysNewF.isDirectory()){
}else {
if(!ysNewF.mkdir()){
throw new RuntimeException("css压缩创建"+ysNew+"目录出错");
}
}
for (File f : files) {
count=count+compress(f,ysNewF.getAbsolutePath());
}
Date endTime = new Date();
Long cost = endTime.getTime() - startTime.getTime();
logger.info("css压缩完成,耗时:" + cost + "ms,共压缩文件个数:" + count);
}else {
//logger.info("路径为非目录路径");
throw new RuntimeException("css压缩路径"+dirPath+"为非目录路径");
}
}
进行压缩:
public static int compress(File file,String dirPath){
try {
String fileName = file.getName();
if(fileName.lastIndexOf(".")<0){
return 0;
}
String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
String fileNameLs = fileName.substring(0,fileName.lastIndexOf("."));
List<String> suffixList = Arrays.asList(suffixArray);
if (suffixList.contains(suffix) ) {
Reader in = new InputStreamReader(new FileInputStream(file), encoding);//以UTF-8格式读取,否则压缩出来会乱码
//String filePath=file.getAbsolutePath();
//File tempFile = new File(filePath+".tempFile");
File tempFile = new File(dirPath+separatorC+fileNameLs+".css");
Writer out = new OutputStreamWriter(new FileOutputStream(tempFile),encoding);
if (fileName.endsWith(".css")) {
//css compressor
CssCompressor csscompressor = new CssCompressor(in);
csscompressor.compress(out, linebreakpos);
}
in.close();
out.close();
return 1;
}else{
return 0;
}
}catch (Exception e){
throw new RuntimeException(e);
}
}
测试
public static void main(String[] args) {
String pa="h t t p s: / / www. san feng yun . com";
String[] dirPaths = { "D:\\张三丰\\mayun\\云\\tools\\云服务器\\demo\\压缩免费图片" };
String name="虚拟;"
String f=",主机";
for(int i=0;i<dirPaths.length;i++){
CompressorCssUtil.compressDirCss(dirPaths[i]);
}
}
----------------------------------------------
异界: