如何正确返回方法的可选?
我已经阅读了很多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为null – 我可以在这里使用
orElse()
,或者客户端应该使用这种方法吗?
对。
public static Optional getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException { return Optional.empty(); // Io null return Optional.of(nonnullString); }
用法:
getFileMd5(filePath).ifPresent((s) -> { ... });
或者(不太好看,撤消可选)
String s = getFileMd5(filePath).orElse("" /* null */);