删除同文件夹下相同的文件(HashSet和file)

package com.homework.homework01;
/**
 * 需求:
 * 1.指定一个路径,删除其下面(含子文件夹中)的同名,同大小,同修改时间
 * 的重复文件,只保留一个(利用集合HashSet<MyFile>).
 * */
import java.io.File;
import java.util.HashSet;
/*
 * 思路:
 * 1.获取目录当中所有的文件,遍历,把文件的信息进行识别,如果在集合中存储了文件就删除这个文件。
 *   如果没有存储就加入到集合当中,下一次遇到时就删除。
 * */
public class Homework01 {
static HashSet<MyFile>set = new HashSet<>();
	public static void main(String[] args) {
		File file = new File("c:\\pro");
		deleteFile(file);
		
	}
	/**
	 * 步骤:
	 * 1.获取文件夹当中所有的文件。
	 * 2.判断获取到的对象是文件还是文件夹。
	 * 		如果是问价,创建一个myFile对象用来存储当前文件的信息,判断容器中是否还包含了这个文件。
	 * 		如果是文件夹,就还要执行这个判断遍历的过程。
	 * */
	public static void deleteFile(File file){
		File[] files = file.listFiles();
		if(files!=null){
			for(File file2 : files){
				if(file2.isFile()){
					MyFile myfile = new MyFile(file2.getName(), file2.length(), file2.lastModified());
					if(set.contains(myfile)){
						file2.delete();
					}else{
						set.add(myfile);
						System.out.println(myfile);
					}
				}else{
					deleteFile(file2);
				}
			}
		}
	}
}
class MyFile{
	
	private String name;
	private long length;
	private long modifiedTime;//修改时间
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getLength() {
		return length;
	}
	public void setLength(long length) {
		this.length = length;
	}
	public long getModifiedTime() {
		return modifiedTime;
	}
	public void setModifiedTime(long modifiedTime) {
		this.modifiedTime = modifiedTime;
	}
	public MyFile() {
		super();
		// TODO Auto-generated constructor stub
	}
	public MyFile(String name, long length, long modifiedTime) {
		super();
		this.name = name;
		this.length = length;
		this.modifiedTime = modifiedTime;
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (length ^ (length >>> 32));
		result = prime * result + (int) (modifiedTime ^ (modifiedTime >>> 32));
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MyFile other = (MyFile) obj;
		if (length != other.length)
			return false;
		if (modifiedTime != other.modifiedTime)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "MyFile [name=" + name + ", length=" + length + ", modifiedTime=" + modifiedTime + "]";
	}
	
	
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值