Library contents

Java Files.size

Measure how many bytes a saved receipt occupies before attaching it to a message.

A simple example

Files.size

  1. Start with A regular file containing ASCII AB
  2. Do this Measure its length
  3. Result 2 bytes
Each ASCII character occupies one byte and this file has no trailing newline.

Syntax

Java 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.java

Check 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.

Result4
Main.java
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);
        }
    }
}
Output
4

The receipt contains the four ASCII bytes in milk. No newline is written.

Advertisements

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.

Result2
Main.java
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);
            }
        }
    }
}
Output
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?

GivenFile contents “clay”
Worked result4

What to watch for

File sizes are measured in bytes. Text character counts can differ.

Documentation for Files.size