首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java常用工具类2 - 崔笑颜的博客

Java常用工具类2 - 崔笑颜的博客

作者头像
崔笑颜
发布2021-02-02 18:00:53
4510
发布2021-02-02 18:00:53
举报

一、当相同元素为String时 方法一

/**
 * List去重
 */
private List<String> removeDuplicate(List<String> list) {
    LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
    set.addAll(list);
    list.clear();
    list.addAll(set);
    return list;
}

方法二

List<String> list= list.stream().distinct().collect(Collectors.toList());

二、当相同元素为对象时 方法一

// 注意Comparator.comparing要根据参数的类型进行选择
private List<GroupVO> removeDuplicateGroupVO(List<GroupVO> groupVOS){
    return groupVOS.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(GroupVO::getId))
                    ), ArrayList::new
            )
    );
}

方法二

// 注意Comparator.comparing要根据参数的类型进行选择
private List<GroupVO> removeDuplicateGroupVO(List<GroupVO> groupVOS){
    return groupVOS.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(GroupVO::getId))
                    ), ArrayList::new
            )
    );
}

方法三

public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
      Map<Object, Boolean> map = new ConcurrentHashMap<>();
      return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
  }
 
// remove duplicate
persons.stream().filter(distinctByKey(p -> p.getId())).forEach(p -> System.out.println(p));

方法一:简单粗暴,直接使用copy(),如果目标存在,先使用delete()删除,再复制;

方法二:使用输入输出流。(代码注释部分)

package eg2;
 
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Scanner;
 
/******************
 * 文件的复制
 *******************/
 
public class Test2_3 {
 
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入指定文件夹路径:");
        String oldpath = sc.next();
        System.out.println("请输入目标文件夹路径:");
        String newpath = sc.next();
        System.out.println("请输入要复制的文件名:");
        String filename = sc.next();
        copy(filename, oldpath, newpath);
        System.out.println("复制完成!");
    }
 
    private static void copy(String filename, String oldpath, String newpath) throws IOException {
        // TODO Auto-generated method stub
        File oldpaths = new File(oldpath + "/" + filename);
        File newpaths = new File(newpath + "/" + filename);
        if (!newpaths.exists()) {
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        } else {
            newpaths.delete();
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        }
 
        // String newfile = "";
        // newfile += newpaths;
        // FileInputStream in = new FileInputStream(oldpaths);
        // File file = new File(newfile);
        // if (!file.exists()) {
        // file.createNewFile();
        // }
        // FileOutputStream out = new FileOutputStream(newpaths);
        // byte[] buffer = new byte[1024];
        // int c;
        // while ((c = in.read(buffer)) != -1) {
        // for (int i = 0; i < c; i++) {
        // out.write(buffer[i]);
        // }
        // }
        // in.close();
        // out.close();
    }
 
}

java实现文件压缩,文件夹压缩,以及文件和文件夹的混合压缩

package util;
 
/**
 * @program: transformation
 * @description:
 * @author: cuixy
 * @create: 2019-07-26 14:30
 **/
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/**
 * 压缩算法类
 * 实现文件压缩,文件夹压缩,以及文件和文件夹的混合压缩
 * @author ljheee
 *
 */
public class CompactAlgorithm {
 
    /**
     * 完成的结果文件--输出的压缩文件
     */
    File targetFile;
 
    public CompactAlgorithm() {}
 
    public CompactAlgorithm(File target) {
        targetFile = target;
        if (targetFile.exists())
            targetFile.delete();
    }
 
    /**
     * 压缩文件
     *
     * @param srcfile
     */
    public void zipFiles(File srcfile) {
 
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(targetFile));
 
            if(srcfile.isFile()){
                zipFile(srcfile, out, "");
            } else{
                File[] list = srcfile.listFiles();
                for (int i = 0; i < list.length; i++) {
                    compress(list[i], out, "");
                }
            }
 
            System.out.println("压缩完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 压缩文件夹里的文件
     * 起初不知道是文件还是文件夹--- 统一调用该方法
     * @param file
     * @param out
     * @param basedir
     */
    private void compress(File file, ZipOutputStream out, String basedir) {
        /* 判断是目录还是文件 */
        if (file.isDirectory()) {
            this.zipDirectory(file, out, basedir);
        } else {
            this.zipFile(file, out, basedir);
        }
    }
 
    /**
     * 压缩单个文件
     *
     * @param srcfile
     */
    public void zipFile(File srcfile, ZipOutputStream out, String basedir) {
        if (!srcfile.exists())
            return;
 
        byte[] buf = new byte[1024];
        FileInputStream in = null;
 
        try {
            int len;
            in = new FileInputStream(srcfile);
            out.putNextEntry(new ZipEntry(basedir + srcfile.getName()));
 
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.closeEntry();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 压缩文件夹
     * @param dir
     * @param out
     * @param basedir
     */
    public void zipDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists())
            return;
 
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }
 
 
 
}
 

运行测试

//压缩测试
File f = new File("/Users/cuixiaoyan/Downloads/浏览器下载");
new CompactAlgorithm(new File( "/Users/cuixiaoyan/Downloads/",f.getName()+".zip")).zipFiles(f);
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021年1月13日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • java实现文件压缩,文件夹压缩,以及文件和文件夹的混合压缩
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档