I read a lot of Java 8. Optional, and I understand the concept, but still have difficulty trying to implement it myself in my code.
Despite the fact that I have a website for good examples, I did not find it with a good explanation.
I have the following 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 the file, passing it the path to the file. As you can see, if the file path does not exist (or is printed incorrectly), a NoSuchFileException is thrown and the method returns Null .
Instead of returning null, I want to use the option, so my method should return Optional <String>, right?
- What is the right way to do it right?
- null -
orElse(),
?