Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get a file's extension and size

Short answer

Take the file name and everything after the last dot:

String extension(Path path) {
    String name = path.getFileName().toString();
    int dot = name.lastIndexOf('.');
    return dot > 0 ? name.substring(dot + 1) : "";
}
 
void main() {
    IO.println(extension(Path.of("docs", "report.final.pdf")));
    IO.println(extension(Path.of("Makefile")));
    IO.println("[" + extension(Path.of(".gitignore")) + "]");
}

Output:

pdf
 
[]

The dot > 0 condition does not treat the name of a hidden file like .gitignore as an extension.

The name without extension

Take the part before the last dot:

void main() {
    String name = Path.of("photos/cat.jpeg").getFileName().toString();
    int dot = name.lastIndexOf('.');
 
    IO.println(dot > 0 ? name.substring(0, dot) : name);
}

Output:

cat

File size

Files.size() returns the size in bytes:

void main() throws IOException {
    Path file = Path.of("data.bin");
    Files.write(file, new byte[2500]);
 
    IO.println(Files.size(file));
}

Output:

2500

A readable size

Divide by 1024 until the number is below 1024:

String readableSize(long bytes) {
    String[] units = {"B", "KB", "MB", "GB", "TB"};
    double size = bytes;
    int unit = 0;
    while (size >= 1024 && unit < units.length - 1) {
        size /= 1024;
        unit++;
    }
    return String.format(Locale.US, "%.1f %s", size, units[unit]);
}
 
void main() {
    IO.println(readableSize(500));
    IO.println(readableSize(2500));
    IO.println(readableSize(3_221_225_472L));
}

Output:

500.0 B
2.4 KB
3.0 GB

Common mistake

Looking for the first dot with indexOf(). For archive.tar.gz you get tar.gz, and for a path with a dot in a folder name you get garbage:

void main() {
    String path = "v1.2/readme";
    IO.println(path.substring(path.indexOf('.') + 1));
}

Output:

2/readme

Take the file name with getFileName() and look for the last dot.

Functions used in this recipe

  • Path.of() — Creates a Path object — a path to a file or folder.
  • String.lastIndexOf() — Finds the position of the last occurrence of a character or a substring.

Thanks for reading!

Donate to the site — we work hard for you.