Java Files.size
Measure how many bytes a saved receipt occupies before attaching it to a message.
A simple example
Files.size
- Start with A regular file containing ASCII AB
- Do this Measure its length
- Result 2 bytes
Syntax
Files.size(path)
JDK 21 declarations (1)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCheck a receipt attachment size
An office is preparing receipts for transfer and needs to budget storage. Identify which size the program measures, especially when a receipt is also stored inside a compressed archive.
import java.nio.file.Files;
class Main {
public static void main(String[] args) throws Exception {
var path = Files.createTempFile("receipt", ".txt");
try {
Files.writeString(path, "milk");
System.out.println(Files.size(path));
} finally {
Files.deleteIfExists(path);
}
}
}
4
The receipt contains the four ASCII bytes in milk. No newline is written.
Budget the bytes for a café label
A printer buffers a limited number of bytes for each label. The shift supervisor tests a one-letter accented label because a count of visible characters alone would underestimate its UTF-8 storage size.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path label = Files.writeString(desk.resolve("label.txt"), "é");
System.out.println(Files.size(label));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
2
The single character is encoded as two UTF-8 bytes.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
What to watch for
File sizes are measured in bytes. Text character counts can differ.