java
36 lines · 7 steps
Streaming a SHA-256 file checksum in Java
Compute a file's SHA-256 hash by feeding its bytes through a DigestInputStream, then render the result as hex.
Explained by
highlit
1public final class FileChecksum {
2
3 private static final char[] HEX = "0123456789abcdef".toCharArray();
4
5 private FileChecksum() {
6 }
7
8 public static String sha256(Path file) throws IOException {
9 MessageDigest digest;
10 try {
11 digest = MessageDigest.getInstance("SHA-256");
12 } catch (NoSuchAlgorithmException e) {
13 throw new IllegalStateException("SHA-256 not available", e);
14 }
15
16 try (InputStream in = Files.newInputStream(file);
17 DigestInputStream dis = new DigestInputStream(in, digest)) {
18 byte[] buffer = new byte[8192];
19 while (dis.read(buffer) != -1) {
20 // draining the stream feeds the digest
21 }
22 }
23
24 return toHex(digest.digest());
25 }
26
27 private static String toHex(byte[] bytes) {
28 char[] out = new char[bytes.length * 2];
29 for (int i = 0; i < bytes.length; i++) {
30 int b = bytes[i] & 0xff;
31 out[i * 2] = HEX[b >>> 4];
32 out[i * 2 + 1] = HEX[b & 0x0f];
33 }
34 return new String(out);
35 }
36}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1DigestInputStream lets you hash data as you read it, avoiding loading the whole file into memory.
- 2Try-with-resources guarantees the stream closes even when reading throws.
- 3Bytes must be masked with 0xff before hex conversion because Java bytes are signed.
Related explainers
java
@Component @Order(20) public class ProductSearchIndexRunner implements ApplicationRunner {
Rebuilding a search index at Spring startup
startup-hook
batching
streaming
Intermediate
8 steps
java
@Service public class OrderCheckoutService { private final OrderRepository orderRepository;
How @Transactional guards a Spring checkout
dependency-injection
transactions
atomicity
Intermediate
6 steps
java
@Service public class OrderMetricsService { private final MeterRegistry registry;
Instrumenting orders with Micrometer in Spring
metrics
micrometer
observability
Intermediate
8 steps
java
@RestController @RequestMapping("/api/files") public class FileUploadController {
Handling secure file uploads in Spring
file-upload
input-validation
path-traversal
Intermediate
10 steps
java
package com.example.fs; import java.io.IOException; import java.nio.file.FileSystems;
Watching a directory with Java NIO
file-io
event-loop
resource-management
Intermediate
8 steps
java
public final class QueryParams { private final Map<String, List<String>> params;
Parsing and building URL query strings in Java
parsing
multimap
url-encoding
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-a-sha-256-file-checksum-in-java-explained-java-5db4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.