Skip to lesson

File size, dates and temporary files

I'm on:

Showing steps for Windows. They are marked “On Windows” below.

Besides its content, every file carries small facts: how many bytes it holds and when it last changed. Programs also often need short-lived temporary files for work in progress, and those must be cleaned up every time.

Files.size and getLastModifiedTime

Files.size(path) returns the file's length in bytes as a long. Bytes are not characters: in UTF-8, A takes 1 byte but the rupee sign ₹ takes 3.

Example 1 · Size in bytes and the last-modified time

SizeAndTimeDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.attribute.FileTime;import java.time.Instant;
public class SizeAndTimeDemo {    public static void main(String[] args) throws IOException {        String plain = "Fee 500";        String rupee = "Fee ₹500";        Path a = Files.writeString(Path.of("fee-plain.txt"), plain);        Path b = Files.writeString(Path.of("fee-rupee.txt"), rupee);
        System.out.println("Plain: " + plain.length() + " characters, " + Files.size(a) + " bytes");        System.out.println("Rupee: " + rupee.length() + " characters, " + Files.size(b) + " bytes");
        Files.setLastModifiedTime(a, FileTime.from(Instant.parse("2025-03-10T04:30:00Z")));        FileTime changed = Files.getLastModifiedTime(a);        System.out.println("Last modified: " + changed);
        Files.delete(a);        Files.delete(b);    }}
Output
Plain: 7 characters, 7 bytes
Rupee: 8 characters, 10 bytes
Last modified: 2025-03-10T04:30:00Z

What this code does

  • Files.writeString stores text as UTF-8, where ₹ needs 3 bytes. So the rupee file has 8 characters but 10 bytes: Files.size always counts bytes.
  • The time is set to a fixed moment so the output is the same on every run. FileTime prints in UTC; the Z at the end means UTC.

Example 2 · Showing a size in KB and MB

SizeFormatDemo.javaJava
public class SizeFormatDemo {    static String formatSize(long bytes) {        if (bytes < 1024) {            return bytes + " B";        }        double kb = bytes / 1024.0;        if (kb < 1024) {            return String.format("%.1f KB", kb);        }        double mb = kb / 1024.0;        if (mb < 1024) {            return String.format("%.1f MB", mb);        }        return String.format("%.1f GB", mb / 1024.0);    }
    public static void main(String[] args) {        long[] sizes = {512, 2_048, 350_000, 5_368_709, 3_221_225_472L};        for (long s : sizes) {            System.out.println(s + " bytes = " + formatSize(s));        }    }}
Output
512 bytes = 512 B
2048 bytes = 2.0 KB
350000 bytes = 341.8 KB
5368709 bytes = 5.1 MB
3221225472 bytes = 3.0 GB

What this code does

  • One KB here is 1024 bytes, the way Windows Explorer counts. Dividing by 1024.0 keeps the decimal part; %.1f shows one digit after the point.
  • Files.size returns a long because files can be larger than 2 GB, the limit of an int. The last size, 3 GB, would not fit in an int.

Files.getLastModifiedTime(path) returns a FileTime, the moment the file's content last changed. Files.setLastModifiedTime(path, time) sets it, which is handy for tests and for tools that copy files. Both throw NoSuchFileException for a missing file.

The rupee sign is written \u20B9 in the examples. A \u escape works in every editor and on every Java version, whatever the source file's encoding.

Converting FileTime to java.time

FileTime has few methods of its own. toInstant() turns it into an Instant, a point on the UTC timeline, and from there the whole java.time API is open: LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata")) gives the time in India, and a DateTimeFormatter prints it.

Example 3 · FileTime to Indian time

FileTimeDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.attribute.FileTime;import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.format.DateTimeFormatter;
public class FileTimeDemo {    public static void main(String[] args) throws IOException {        Path notes = Files.writeString(Path.of("dbms-notes.txt"), "Unit 3: joins");        Files.setLastModifiedTime(notes, FileTime.from(Instant.parse("2025-03-10T04:30:00Z")));
        FileTime ft = Files.getLastModifiedTime(notes);        Instant instant = ft.toInstant();        LocalDateTime india = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));        DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
        System.out.println("FileTime : " + ft);        System.out.println("Instant  : " + instant);        System.out.println("India    : " + india.format(f));        System.out.println("Millis   : " + ft.toMillis());        System.out.println("Round trip equal? " + FileTime.from(instant).equals(ft));
        Files.delete(notes);    }}
Output
FileTime : 2025-03-10T04:30:00Z
Instant  : 2025-03-10T04:30:00Z
India    : 10-03-2025 10:00
Millis   : 1741581000000
Round trip equal? true

What this code does

  • toInstant() turns the FileTime into an Instant. India is 5 hours 30 minutes ahead of UTC, so 04:30 UTC shows as 10:00 in Asia/Kolkata.
  • toMillis() gives milliseconds since 1 January 1970 UTC, and FileTime.from(instant) converts back without losing anything.

Example 4 · Which notes changed after the exam notice?

ChangedSinceDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.attribute.FileTime;import java.time.Duration;import java.time.Instant;import java.util.LinkedHashMap;import java.util.Map;
public class ChangedSinceDemo {    public static void main(String[] args) throws IOException {        Path dir = Files.createDirectories(Path.of("notes"));        Map<String, String> changedAt = new LinkedHashMap<>();        changedAt.put("java.txt", "2025-02-20T09:00:00Z");        changedAt.put("dbms.txt", "2025-03-03T15:00:00Z");        changedAt.put("os.txt", "2025-03-08T06:30:00Z");
        for (Map.Entry<String, String> e : changedAt.entrySet()) {            Path p = Files.writeString(dir.resolve(e.getKey()), "notes");            Files.setLastModifiedTime(p, FileTime.from(Instant.parse(e.getValue())));        }
        Instant notice = Instant.parse("2025-03-01T06:30:00Z");        for (String name : changedAt.keySet()) {            Instant t = Files.getLastModifiedTime(dir.resolve(name)).toInstant();            if (t.isAfter(notice)) {                long days = Duration.between(notice, t).toDays();                System.out.println(name + ": changed " + days + " days after the notice");            } else {                System.out.println(name + ": not changed since the notice");            }        }
        for (String name : changedAt.keySet()) {            Files.delete(dir.resolve(name));        }        Files.delete(dir);    }}
Output
java.txt: not changed since the notice
dbms.txt: changed 2 days after the notice
os.txt: changed 7 days after the notice

What this code does

  • Each file gets a fixed time, then the program reads the times back and compares the Instants with isAfter.
  • Duration.between(notice, t).toDays() counts whole days: from 1 March 06:30 to 3 March 15:00 is 2 days and some hours, so it prints 2. Backup and sync tools use exactly this kind of check.

The other way, FileTime.from(instant) makes a FileTime. To compare two files, compare their instants with isBefore and isAfter, or measure the gap with Duration.between.

createTempFile and createTempDirectory

Files.createTempFile(prefix, suffix) creates a new, empty file with a unique name in the system's temp folder, such as marks-8150312470596313210.csv. Files.createTempDirectory(prefix) does the same for a folder. Both return the new Path.

On Windows

On Windows, java.io.tmpdir is your temp folder, so Files.createTempFile puts files in C:\Users\Priya\AppData\Local\Temp (your user name will differ).

Windows PowerShell
PS C:\Users\Priya> echo $env:TEMPC:\Users\Priya\AppData\Local\Temp

Example 5 · Temporary files and folders

TempDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class TempDemo {    public static void main(String[] args) throws IOException {        Path tmpDir = Path.of(System.getProperty("java.io.tmpdir"));
        Path tmp = Files.createTempFile("marks-", ".csv");        String name = tmp.getFileName().toString();        System.out.println("Starts with marks-? " + name.startsWith("marks-"));        System.out.println("Ends with .csv?     " + name.endsWith(".csv"));        System.out.println("In the temp folder? " + Files.isSameFile(tmp.getParent(), tmpDir));        System.out.println("Empty at start?     " + (Files.size(tmp) == 0));
        Path work = Files.createTempDirectory("report-");        Path part = Files.createTempFile(work, "part-", ".txt");        System.out.println("Part inside work?   " + part.getParent().equals(work));
        Files.delete(part);        Files.delete(work);        Files.delete(tmp);        System.out.println("All cleaned up?     " + (Files.notExists(tmp) && Files.notExists(work)));    }}
Output
Starts with marks-? true
Ends with .csv?     true
In the temp folder? true
Empty at start?     true
Part inside work?   true
All cleaned up?     true

What this code does

  • The full name has a random number between the prefix and the suffix, so it changes on every run; the program checks only the parts you chose. Files.isSameFile checks that two paths lead to the same folder.
  • Temporary files are not deleted for you. The program deletes the part file, then the work folder, then the first temp file.

The temp folder is stored in the system property java.io.tmpdir. To create a temp file inside your own folder instead, pass it first: Files.createTempFile(workDir, "part-", ".txt"). The random part makes clashes very unlikely, so two runs of the program, or two users, never fight over the same name.

Why deleteOnExit is not enough

file.deleteOnExit() (a method of the old File class) asks Java to delete the file when the JVM ends. It sounds easy, but it often fails; the reasons come after the code.

Example 6 · A temp folder that cleans itself up

TempFolderDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
class TempFolder implements AutoCloseable {    private final Path dir;    private final List<Path> files = new ArrayList<>();
    TempFolder(String prefix) throws IOException {        dir = Files.createTempDirectory(prefix);    }
    Path dir() {        return dir;    }
    Path newFile(String name, String text) throws IOException {        Path p = Files.writeString(dir.resolve(name), text);        files.add(p);        return p;    }
    @Override    public void close() throws IOException {        for (Path p : files) {            Files.deleteIfExists(p);        }        Files.deleteIfExists(dir);    }}
public class TempFolderDemo {    public static void main(String[] args) throws IOException {        Path first;        try (TempFolder tmp = new TempFolder("result-")) {            first = tmp.dir();            tmp.newFile("sem1.csv", "21,88");            tmp.newFile("sem2.csv", "21,91");            System.out.println("Inside try, folder exists? " + Files.exists(first));        }        System.out.println("After try, folder exists?  " + Files.exists(first));
        Path second = null;        try (TempFolder tmp = new TempFolder("result-")) {            second = tmp.dir();            tmp.newFile("sem3.csv", "21,79");            throw new IllegalStateException("bad marks row");        } catch (IllegalStateException e) {            System.out.println("Failed: " + e.getMessage());        }        System.out.println("After a failure, exists?   " + Files.exists(second));    }}
Output
Inside try, folder exists? true
After try, folder exists?  false
Failed: bad marks row
After a failure, exists?   false

What this code does

  • TempFolder remembers every file it makes, and close() deletes them and then the folder. try-with-resources calls close() when the block ends.
  • In the second block an exception is thrown, yet the folder is still gone: close() runs before the catch. deleteOnExit would have waited for the JVM to end, and not at all after a crash.
  • It runs only on a normal exit. A crash, a kill from Task Manager, an IDE stop button or a power cut skips it.
  • Each registered path stays in memory until the JVM ends, so a server that runs for weeks slowly fills up.
  • It cannot delete a folder that still has files in it.
Delete temporary files yourself, as soon as you are done: in a finally block or, better, in a small AutoCloseable class used with try-with-resources.

Next step

Check your understanding

11 quick questions