提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
简单记录,方便日后查看
通过调用windows系统自带计算工具Get-FileHash,计算文件SHA256 hash值
一、使用步骤
1.代码实现
代码如下(示例):
public class test {
public static void main(String[] args) throws Exception {
System.out.println(SHA256Hex("C://Users//zhx//Desktop//vsjitdebuggerui.dll"));//文件路径
}
private static String SHA256Hex(String filepath) throws Exception {
Runtime runtime = Runtime.getRuntime();
try {
String[] command = {"powershell.exe","Get-FileHash",filepath,"|","Format-List|findstr","Hash"};
Process process = runtime.exec(command);
String inStr = consumeInputStream(process.getInputStream());//标准输入流
/*int proc = process.waitFor();
if (proc == 0) {
} else {
System.out.println("执行失败");
}*/
return inStr;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
private static String consumeInputStream(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
String s;
StringBuilder sb = new StringBuilder();
while ((s = br.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
String s1=sb.toString();
String str[]=s1.split(": ");
return str[1];
}
}
二、总结
Windows PowerShell
Format-List 将输出的格式设置为属性列表,其中每个属性均各占一行显示。参考文档
Get-FileHash参考手册