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
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
java
@Configuration public class DataSourceLoggingConfig { @Bean
Wrapping a Spring DataSource for query tracing
proxy pattern
observability
data source
Intermediate
7 steps
rust
use axum::body::Bytes; use axum::http::{header, HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use serde::Serialize;
Custom Axum responses with per-user ETags
etag
trait-implementation
generics
Intermediate
7 steps
java
@RestController @RequestMapping("/api/products") @Validated public class ProductSearchController {
Validating query params in a Spring controller
validation
pagination
rest-api
Intermediate
8 steps
java
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = PasswordsMatchValidator.class) public @interface PasswordsMatch {
Custom cross-field validation in Spring
bean-validation
custom-constraints
cross-field-validation
Intermediate
8 steps
java
public final class LogRedactor { private static final Pattern SECRET = Pattern.compile( "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");
Streaming log redaction in Java
regex
streaming-io
try-with-resources
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.