问题
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.
I have the next method:
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;
}
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.
Instead of returning null, I want to use Optional, so my method should return Optional <String>, right?
- 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?
回答1:
Right.
public static Optional<String> getFileMd5(String filePath)
throws NoSuchAlgorithmException, IOException {
return Optional.empty(); // I.o. null
return Optional.of(nonnullString);
}
Usage:
getFileMd5(filePath).ifPresent((s) -> { ... });
or (less nice as undoing the Optional)
String s = getFileMd5(filePath).orElse("" /* null */);
来源:https://stackoverflow.com/questions/37811794/how-to-properly-return-optional-of-a-method