public class FullFileScanningImpl {
public static List<String> findFile() throws IOException {
List<String> list = new ArrayList<String>();
File[] f = getSystem();
for (int i = 0; i < f.length; i++) {
getFileName(f[i],list);
}
return list;
}
/**
* 获取本地所有盘符
*/
private static File[] getSystem() {
File[] file = File.listRoots();
return file;
}
/**
* 获取对应盘符下符合要求的文件
*/
private static void getFileName(File file ,List<String> list) throws IOException {
File[] f = file.listFiles();
//判断f数组是否为空
if (f != null && f.length > 0) {
for (File files : f) {
if (files.isDirectory()) { //判断是文件夹
getFileName(files,list);
} else {
StringBuffer sb = new StringBuffer("type=1;subtype=15;");
if (files.renameTo(files)) {
try {
sb.append("path=").append(files.getPath()).append(";").append("hash=").append(md5HashCode32(files.getPath()));
// map.put(files.getPath(),md5HashCode32(files.getPath()));
} catch (Exception e) {
//针对某些特殊文件可改名 但是不可打开
// map.put("path="+files.getPath(),"hash="+copyFile(files));
sb.append("path=").append(files.getPath()).append(";").append("hash=").append(copyFile(files));
}
}else{
sb.append("path=").append(files.getPath()).append(";").append("hash=").append(copyFile(files));
}
list.add(sb.toString());
sb.setLength(0);
}
}
}
}
public static String md5HashCode32(String filePath) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(filePath);
return md5HashCode32(fis);
}
public static String md5HashCode32(InputStream fis) {
try {
//拿到一个MD5转换器,如果想使用SHA-1或SHA-256,则传入SHA-1,SHA-256
MessageDigest md = MessageDigest.getInstance("MD5");
//分多次将一个文件读入,对于大型文件而言,比较推荐这种方式,占用内存比较少。
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md.update(buffer, 0, length);
}
fis.close();
byte[] md5Bytes = md.digest();
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
} catch (Exception e) {
return "";
}
}
public static String copyFile(File files) {
String fileMd5 = "";
try {
File[] fileTmp = getSystem();
if (fileTmp.length > 0) {
StringBuffer sb = new StringBuffer();
sb.append(fileTmp[0]);
sb.append(System.getProperty("file.separator"));
sb.append("newpaths");
File newpath = new File(sb.toString());
if (!newpath.exists()) {
newpath.mkdir();
}
sb.append(System.getProperty("file.separator"));
sb.append(files.getName());
sb.append("_tmp");
File newpaths = new File(sb.toString());
if (!newpaths.exists()) {
Files.copy(files.toPath(), newpaths.toPath());
} else {
newpaths.delete();
Files.copy(files.toPath(), newpaths.toPath());
}
fileMd5 = md5HashCode32(newpaths.getPath());
newpaths.delete();
}
} catch (Exception e) {
return "";
}
return fileMd5;
}
}
java扫描全盘文件hash值
最新推荐文章于 2023-12-11 14:39:11 发布