您当前的位置: 首页 > 

梁云亮

暂无认证

  • 1浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

文件压缩

梁云亮 发布时间:2019-12-05 09:22:56 ,浏览量:1

相关博客: 功能强大的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();
    }
}
说明:

真正使用时,应该在压缩之前应该把文件中的注释行给删除掉。

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0394s