目标:读取文件的MD5值,文件大小,文件最后修改时间,文件名称,并将这些值写到文件中去
代码实践如下:
public class Test_1 {
public static void main(String[] args) {
String readPath = "D:\\Users\\test"; //读取文件的路径
String writerPath="D:\\test\\2.txt"; //写入文件路径
getFileMd5(readPath,writerPath);
}
/**
* 获取文件信息
* @param path
*/
public static void getFileMd5(String readPath,String writerPath){
File file = new File(readPath);
if(file.isDirectory()){ //判断是否文件夹
File[] files = file.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
getFileMd5(files[i].getPath(),writerPath);
}else{
if(files[i].canRead()){
//获取文件路径
String filePath = files[i].getPath();
//获取文件MD5
String fileMD5 = testMD5(filePath);
//获取文件名称
String fileName = files[i].getName();
//获取文件最后修改时间
String fileTime = getModifyTime(filePath);
String fileInformation =filePath+file.separator+fileMD5+file.separator+fileName+file.separator+fileTime;
writeDocment(fileInformation,writerPath);
System.out.println(fileInformation);
}
}
}
}else{
if(file.canRead()){
String filePath = file.getPath();
//获取文件MD5
String fileMD5 = testMD5(filePath);
//获取文件名称
String fileName = file.getName();
//获取文件最后修改时间
String fileTime = getModifyTime(filePath);
String fileInformation =filePath+file.separator+fileMD5+file.separator+fileName+file.separator+fileTime;
writeDocment(fileInformation,writerPath);
System.out.println(fileInformation);
}
}
return;
}
/**
* 计算文件MD5值
*/
public static String testMD5(String readPath){
BigInteger bi = null;
File file = new File(readPath);
FileInputStream im=null;
BufferedInputStream bf = null;
try {
im = new FileInputStream(file);
bf= new BufferedInputStream(im);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = new byte[1024];
int len =0;
while((len = bf.read(bytes))!=-1){
md.update(bytes);
}
bf.close();
im.close();
byte[] b = md.digest();
bi = new BigInteger(1, b);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bi.toString();
}
/**
* 文件最后修改时间
*/
public static String getModifyTime(String path){
File file = new File(path);
SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fileTime = sm.format(file.lastModified());
return fileTime;
}
/**
* 将获取的文件信息写入到指定文件中
*/
public static void writeDocment(String fileInformation,String paths){
File file = new File(paths);
try{
boolean append = true;
FileWriter fw = new FileWriter(file, append);
BufferedWriter bw= new BufferedWriter(fw);
bw.write(fileInformation);
bw.newLine();
bw.flush();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}