【发布时间】:2014-07-30 15:57:05
【问题描述】:
我想计算以 Java 中某个扩展名结尾的文件的 MD5 哈希值。我为此使用了两个代码:
文件搜索.java
public class FileSearch
{
public static File findfile(File file) throws IOException
{
String drive = (new DetectDrive()).USBDetect();
Path start = FileSystems.getDefault().getPath(drive);
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
{
if (file.toString().endsWith(".raw"))
{
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
});
return file;
}
public static void main(String[] args) throws IOException
{
Hash hasher = new Hash();
try
{
if (file.toString().endsWith("raw"))
{
hasher.hash(file);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
哈希.java
public class Hash
{
public void hash(File file) throws Exception
{
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(file);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1)
{
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++)
{
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Digest(in hex format):: " + sb.toString());
}
}
第一个代码用于搜索以 .raw 结尾的文件,而第二个代码(尚未完成)用于获取原始文件,然后计算其哈希值。但是,我不知道如何将第一个代码调用到第二个代码中以获取该原始文件。我相信我必须在 new FileInputStream(...) 中放入一个字符串,但我需要调用原始文件。
是否可以这样做,因为它们都包含一个 main 方法?或者我是否需要在没有 main 方法的情况下更改 FileSearch.java 并改为使用“public String search()”,然后在第二个代码中调用它?如果您能告诉我如何以正确的方式进行操作,我将不胜感激。
【问题讨论】:
标签: java hash md5 file-extension