java如何在用户选择目录元哈希值时输出该值?
这里是初学者,我需要我的程序为3件事输出哈希值:
- 档案
- 目录
- 目录元
我已经让文件和目录工作,但我就是不知道如何做的目录元散列值。到目前为止,当用户进入目录并选择选项“2”时,将显示目录元,但没有哈希值。所以我所需要的就是让程序输出目录meta的哈希值和所有其他输出。我的代码如下所示:(提前感谢任何帮助我的人)
主类
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws IOException {
Scanner Scanscan = new Scanner(System.in);
HashFunction hf = new HashFunction();
System.out.println("Input File or Directory Path:");
while(true) {
String filename = Scanscan.nextLine();
File inputFile = new File(filename);
long hash = 0;
if(filename.equals("exit")){
if (inputFile.isFile()) {
hash = hf.produceFileHash(inputFile.getAbsolutePath());
System.out.println(String.format("The File Hash Value is: %016X", hash));
} else if (inputFile.isDirectory()) {
System.out.println("Please choose either '1' - Directory Hash OR '2' - Directory Meta");
String Choice = Scanscan.nextLine();
if (Choice.equals("1")) {
hash = hf.produceDirHash(inputFile.getAbsolutePath());
System.out.println(String.format("The Directory Hash Value is: %016X", hash));
//System.exit(0);
} else if (Choice.equals("2")) {
hash = hf.produceDirMetaHash(inputFile.getAbsolutePath());
}
}
}
}
}
}
HashChecker类
public interface HashChecker {
long produceFileHash(String filename);
long produceDirHash(String path);
long produceDirMetaHash(String path);
}
哈希函数类
@Override
public long produceDirMetaHash(String path) {
int FileCount = 0;
File dirmeta = new File(path);
File[] listOfFiles = dirmeta.listFiles();
for (File listOfFile : listOfFiles) {
Path file = listOfFile.toPath();
BasicFileAttributes attr = null;
try {
attr = Files.readAttributes(file, BasicFileAttributes.class);
} catch (IOException e) {
e.printStackTrace();
}
if (listOfFile.isFile()) {
FileCount++;
System.out.println("\nFile Number: " + FileCount);
System.out.println("File Name: " + listOfFile.getName());
System.out.println("Path: " + listOfFile.getPath());
System.out.println("Created: " + attr.creationTime());
System.out.println("Last Accessed: " + attr.lastAccessTime());
System.out.println("Last Modified: " + attr.lastModifiedTime());
System.out.println("Regular File: " + attr.isRegularFile());
System.out.println("Size: " + attr.size());
System.out.println("File Name " + listOfFile.getName());
System.out.println("Path " + listOfFile.getPath());
FileCount++;
System.out.println("File Number " + FileCount);
}
}
return FileCount;
}
}
Example of the hash output i need but instead for directory meta
# 1 楼答案
您可以使用以下方法:
ByteArrayOutputStream
封装在^{对于
FileTime
类型,使用toInstant()
方法将它们转换为Serializable