相关博客: 功能强大的Paths类和Files类 正则表达式
代码实现public class FileCompressUtil {
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s+|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll(" ");
}
return dest;
}
public static void main(String[] args) throws IOException {
//读文件
StringBuffer sb = new StringBuffer();
BufferedReader br = Files.newBufferedReader(Paths.get("index.html"), StandardCharsets.UTF_8);
//注意:如果指定的字符编码不对,可能会抛出MalformedInputException异常
String res = null;
while ((res = br.readLine()) != null) {
sb.append(res);
}
br.close();
//压缩测试
System.out.println(sb);
System.out.println(FileCompressUtil.replaceBlank(sb.toString()));
//输出压缩文件
BufferedWriter bw = Files.newBufferedWriter(Paths.get("res.html"), StandardCharsets.UTF_8);
bw.write(FileCompressUtil.replaceBlank(sb.toString()));
bw.flush();
bw.close();
}
}
说明:
真正使用时,应该在压缩之前应该把文件中的注释行给删除掉。