0

Currently, my code snippet:

Path destinationFilepath = Paths.get("/tmp/a/b/c/" + UUID.randomUUID().toString());
FileUtils.createParentDirectories(path.toFile());
destinationFilepath = Files.createFile(path);
File destinationFile = destinationFilepath.toFile();

MessageDigest md5Digest = MessageDigest.getInstance(SHA_256);

String hash = null;
try (FileOutputStream multipartFileOutputStream = FileUtils.openOutputStream(destinationFile);
        DigestOutputStream digestOutputStream = new DigestOutputStream(multipartFileOutputStream, md5Digest)) {
    IOUtils.copyLarge(fileItemStream.openStream(), digestOutputStream);
    digestOutputStream.flush();
    byte[] digest = digestOutputStream.getMessageDigest().digest();
    hash = Hex.encodeHexString(digest);
} catch (IOException e) {
    Files.deleteIfExists(path);
}

As you can see, I'm digesting an InputStream in order to get SHA_256 checksum. Shortly, In order to get that, I'm channing an DigestOutputStream to the file OutputStream.

Currently, I'm creating the file with a random UUID name.

I'd like to directly create the file with name to "checksum hash code".

I'm aware I can rename it, but I'd like to know if could there be any approach to directly create the filename with its checksum code.

Is it possible? Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • `MessageDigest` has a `toString` method that "Returns a string representation of this message digest object.". What is the problem here? – Abhijit Sarkar Apr 17 '23 at 09:28
  • 6
    Since you only compute the digest while writing the file, you can't really know the final digest value when you first create the file. Creating it with a temp name and renaming afterwards is the appropriate thing to do here. An alternative would be to buffer the whole file in memory, but you *probably* don't want to do that. – Joachim Sauer Apr 17 '23 at 09:30

0 Answers0