如何正确返回Optional<>方法? [英] How to properly return Optional<> of a method?
问题描述
我已经阅读了很多Java 8 Optional并且我理解这个概念,但是在我的代码中尝试实现它时仍然遇到困难。
I have read a lot of Java 8 Optional and I do understand the concept, but still get difficulties when trying to implement it myself in my code.
虽然我我已经在网上找到了很好的例子,我没有找到一个很好的解释。
Although I have serached the web for good examples, I didn't found one with good explanation.
我有下一个方法:
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 。
This simple method returns the md5 of a file, by passing it the file path. As you can notice, if the file path doesn't exists (or wrong typed) a NoSuchFileException get thrown and the method return Null.
我想使用Optional,而不是返回null,所以我的方法应该返回 Optional< String>
,对吗?
Instead of returning null, I want to use Optional, so my method should return Optional <String>
, right?
- 正确的做法是什么?
- 如果返回的String为null - 我可以吗?在这里使用
orElse()
,或者这个
类的方法应该由客户端使用?
- What is the proper way of doing it right?
- If the returned String is null - can I use here
orElse()
, or this kind of method should be used by the client side?
推荐答案
正确。
public static Optional<String> getFileMd5(String filePath)
throws NoSuchAlgorithmException, IOException {
return Optional.empty(); // I.o. null
return Optional.of(nonnullString);
}
用法:
getFileMd5(filePath).ifPresent((s) -> { ... });
或(撤销可选的不太好)
or (less nice as undoing the Optional)
String s = getFileMd5(filePath).orElse("" /* null */);
这篇关于如何正确返回Optional<>方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!