gpt4 book ai didi

java - 如何正确返回方法的 Optional<>?

转载 作者:搜寻专家 更新时间:2023-10-30 21:15:14 25 4
gpt4 key购买 nike

我已经阅读了很多 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> ,对吧?

  1. 正确的做法是什么?
  2. 如果返回的字符串为 null - 我可以在这里使用 orElse() , 或这个客户端应该使用什么样的方法?

最佳答案

没错。

public static Optional<String> getFileMd5(String filePath)
throws NoSuchAlgorithmException, IOException {

return Optional.empty(); // I.o. null

return Optional.of(nonnullString);
}

用法:

getFileMd5(filePath).ifPresent((s) -> { ... });

或者(不如撤消 Optional 好)

String s = getFileMd5(filePath).orElse("" /* null */);

关于java - 如何正确返回方法的 Optional<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37811794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com