我已经阅读了很多Java 8 Optional,我确实理解了这个概念,但是在我的代码中尝试自己实现它时仍然遇到了困难。
虽然我已经在网上找到了很好的例子,但我没有找到一个有很好解释的网站。
我有下一个方法:
public static String getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException {
AutomationLogger.getLog().info("Trying getting MD5 hash from file: " + filePath);
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream inputStream;
try {
inputStream = Files.newInputStream(Paths.get(filePath));
} catch (NoSuchFileException e) {
AutomationLogger.getLog().error("No such file path: " + filePath, e);
return null;
}
DigestInputStream dis = new DigestInputStream(inputStream, md);
byte[] buffer = new byte[8 * 1024];
while (dis.read(buffer) != -1);
dis.close();
inputStream.close();
byte[] output = md.digest();
BigInteger bi = new BigInteger(1, output);
String hashText = bi.toString(16);
return hashText;
}
这个简单的方法通过传递文件路径来返回文件的md5。 您可以注意到,如果文件路径不存在(或键入错误),则会抛出 NoSuchFileException ,并且方法返回 Null 。
我想使用Optional,而不是返回null,所以我的方法应该返回Optional <String>
,对吗?
orElse()
,或者这个
客户端应该使用哪种方法?答案 0 :(得分:32)
右。
public static Optional<String> getFileMd5(String filePath)
throws NoSuchAlgorithmException, IOException {
return Optional.empty(); // I.o. null
return Optional.of(nonnullString);
}
用法:
getFileMd5(filePath).ifPresent((s) -> { ... });
或(撤销可选的不太好)
String s = getFileMd5(filePath).orElse("" /* null */);